Python使用filter map reduce的简单例子

第一个print是100内的质数列表。
第二个是列表的数字求和
第三个是列表数字换成它的平方数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python

def is_prime(x):
if x<=1:
return False
for i in range(2,x):
if x % i == 0:
return False
return True

if __name__ == '__main__':
n = [x for x in range(1,101)] # 生成1-199的列表
print(filter(is_prime,n)) # 筛选出100内的质数
print(reduce(lambda x,y:x+y,n)) # 用reduce特性求和
print(map(lambda x:x*x,n)) # 用map求平方

Output:

1
2
3
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
5050
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200]

参考资料:
PEP 8 – Style Guide for Python Code

关注公众号 尹安灿