Python3函数式编程小结

Python函数式编程

  • map(函数,可迭代式)映射函数
  • filter(函数,可迭代式)过滤函数
  • reduce(函数,可迭代式)规约函数
  • lambda函数
  • 列表推导式
  • zip()函数

1列表推导式

#list(range(1,11))  结果为[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = [item for item in range(1,8)]
print(x)
[1, 2, 3, 4, 5, 6, 7]
x = [item for item in range(1,8) if item % 2 == 0]
print(x)
[2, 4, 6]
area = [(x,y) for x in range(1,5) for y in range(1,5) if x!=y]
print(area)
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
dict(area) # 采用字典对area列表打包,相同的键的元素,后面覆盖前面的键
{1: 4, 2: 4, 3: 4, 4: 3}
['The number: %s' % n for n in range(1,4)]
['The number: 1', 'The number: 2', 'The number: 3']
dict1 = {'1':'A','2':'B','3':'C','4':'D'}
[k + '=' + v for k, v in dict1.items()]
['1=A', '2=B', '3=C', '4=D']

2 lambda函数

  • lambda 参数: 表达式(expression)
  • 用于简单函数的定义
  • 返回值就是函数体中的表达式的求值结果
lambda x,y: x*y
<function __main__.<lambda>>
(lambda x,y: x*y)(9,9)
81
f = lambda x,y: x/y
f(10,2)
5.0

3 map()函数

  • map(function, iterable, ...)
  • 返回结果为map迭代式
list(map(lambda x : x**3,[1,2,3,4]))
[1, 8, 27, 64]
list(map(lambda x,y:x+y, [1,2,3,4],[4,5,6,7]))
[5, 7, 9, 11]

4 reduce()函数

  • reduce(函数,迭代式)
  • 对迭代式中的元素按函数依次计算后返回唯一结果
from functools import reduce
reduce((lambda x,y:x+y), [1,2,3,4]) # 等价于 1+2+3+4
10
reduce((lambda x,y:x+y), [1,2,3,4], 90) # 等价于 90+1+2+3+4
100
reduce((lambda x,y:x/y), [1,2,3,4,5]) # 等价于 1/2/3/4/5=1/120
0.008333333333333333

5 filter()函数

  • filter(函数, iterable)
  • 如果第一个参数是一个函数,那么将第二个可迭代数据里的每一个元素作为函数的参数进行计算,把返回Ture的值筛选出来
  • 过滤器的作用是过滤到我们不关心的数据,保留有用的数据
list(filter(None,[11,1,2,0,0,0,False,True]))
[11, 1, 2, True]
list(filter(lambda x:x%2, range(1,11)))
[1, 3, 5, 7, 9]
list(filter(lambda x: x.isalpha(),'a11b22c33d44'))
['a', 'b', 'c', 'd']
tuple(filter(lambda x: x.isalpha(),'a11b22c33d44'))
('a', 'b', 'c', 'd')
set(filter(lambda x: x.isalpha(),'a11b22c33d44'))
{'a', 'b', 'c', 'd'}
list(filter(lambda x:x>4, [1,2,3,4,5,6,7]))
[5, 6, 7]
set(filter(lambda x:x>4, [1,2,3,4,5,6,7]))
{5, 6, 7}

6 zip()函数

  • 参数:元组、列表、字典等迭代器。
  • zip(x1)从x1中依次取一个元组,组成一个元组
  • zip(x1,x2)分别从x1和x2依次各取出一个元素组成元组,所有元组组合成一个新的迭代器
x1 = [1, 2, 3, 4]
z = zip(x1)
print(type(z))
print(list(z))
<class 'zip'>
[(1,), (2,), (3,), (4,)]
x1 = [1,2,3,4,5]
x2 = [6,7,8,9,10]
z1 = zip(x1,x2)
print(list(z1))
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

猜你喜欢

转载自www.cnblogs.com/brightyuxl/p/8947480.html
今日推荐