Python 学习 -01
总结学习了一下Python 函数式编程.
对于Python 的所有函数, 有以下特点:
在运行时创建
在数据结构中分配变量或元素
作为函数的参数传递
作为函数的结果返回
Python中的所有函数都可以用作高阶函数。
学习了一下函数: 上code.
#函数式编程: global+ 变量 的处理。
a =5
def some_fun():
#global a
a =8
some_fun()
print(a)
#Python中的递归函数 这里看似很简单。。。 哈哈
def factorial(n):
if n ==1:
return 1
else:
return n * factorial(n-1)
print(factorial(8))
#看下迭代器
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current >self.high:
raise StopIteration
else:
self.current +=1
return self.current -1
for cin Counter(3,8):
print(c)
#下例函数是 对list中每个元素进行求平方
x = [1,2,3,4,5,6]
def square(num):
return num*num
print(list(map(square,x)))
#简化。。 使用lambda 匿名函数
square =lambda x : x * x
print(square(8))
print(list(map(lambda x: x*x, x)))
#list 求元素的乘积。
product =1
x = [2,4,6,8,10]
for numin x:
product = product * num
print(product)
#简化上述函数处理,使用reduce ===> reduce(function,list)
#获得相同的功能,代码更短,并且在使用函数式编程的情况下更整洁。(注:reduce函数在Python3中已不是内置函数,需要从functools模块中导入)
from functoolsimport reduce
product = reduce((lambda x, y: x*y), x)
print(product)
#filter 过滤 函数===> filter(function, list)
#如果该函数返回True,则不执行任何操作。如果返回False,则从列表中删除该项。
x =range(-5,10)
new_list = []
for numin x:
if num <0:
new_list.append(num)
print(new_list)
#使用filter 过滤 函数
y =list(filter(lambda num:num<0, x))#[-5, -4, -3, -2, -1]
z =list(filter(lambda number: number>0, x))#[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(y)
print(z)
#函数嵌套
def summartion(num):
return sum(num)
def action(func, number):
return func(number)
print(action(summartion, [2,3,4,5,6]))
def rtnJohn():
return "John"
def rtnTom():
return "Tom"
def rtnPerson():
age =int(input("What is your age?"))
if age >=21:
return rtnJohn()
else:
return rtnTom()
列表推导仅适用于列表。map, filter适合任何可迭代的对象.