标签:保留 filter 规约 ssi zip函数 返回值 set ble 函数的参数
函数式编程可以使代码更加简洁,易于理解。Python提供的常见函数式编程方法如下:
#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‘]
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
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]
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
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}
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)]
标签:保留 filter 规约 ssi zip函数 返回值 set ble 函数的参数
原文地址:https://www.cnblogs.com/brightyuxl/p/8947480.html