Skip to content

Commit 313386e

Browse files
committed
函数式编程
1 parent bc3f4ca commit 313386e

File tree

4 files changed

+117
-0
lines changed

4 files changed

+117
-0
lines changed

函数式编程/return_fun.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#函数作为返回值
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#filter()函数用于过滤序列。
2+
3+
4+
#filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
5+
6+
#在一个list中,删掉偶数,只保留奇数,可以这么写:
7+
8+
def is_odd(n):
9+
return n % 2 == 1
10+
11+
list(filter(is_odd,[1,2,4,5,6,7,8,15])) #[1, 5, 7, 15]
12+
13+
#把一个序列中的空字符串删掉
14+
15+
def not_empty(s):
16+
return s and s.strip() #移除字符串头尾指定的字符(默认为空格或换行符)或字符序列 # 去除首尾空格
17+
18+
list(filter(not_empty,['A','','b',None])) #['A', 'b']
19+
20+
21+
22+
#1000以内的素数打印 埃氏筛法
23+
def main():
24+
for n in primes():
25+
if n < 1000:
26+
print(n)
27+
else:
28+
break
29+
30+
def _odd_iter(): # 一个从3开始的奇数序列:偶数肯定不是素数 生成器 一个无限序列
31+
n = 1
32+
while True:
33+
n = n + 2
34+
yield n
35+
36+
def _not_divisible(n): #筛选函数
37+
return lambda x: x % n > 0 #埃氏筛法
38+
39+
def primes(): #定义一个生成器,不断返回下一个素数
40+
yield 2 #先返回第一个素数2
41+
it = _odd_iter() # 初始序列
42+
while True:
43+
n = next(it) # 返回序列的第一个数
44+
yield n
45+
it = filter(_not_divisible(n), it) ## 构造新序列
46+
47+
if __name__ == '__main__':
48+
main()
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#map() map()函数接收两个参数,一个是函数,一个是Iterable map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
2+
3+
4+
def f(x):
5+
return x * x
6+
7+
8+
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8])
9+
print(list(r)) #[1, 4, 9, 16, 25, 36, 49, 64]
10+
11+
#把这个list所有数字转为字符串:
12+
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9
13+
])) #['1', '2', '3', '4', '5', '6', '7', '8', '9']
14+
15+
#reduce
16+
#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,
17+
18+
#reduce把结果继续和序列的下一个元素做累积计算, reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
19+
20+
#对一个序列求和,就可以用reduce实现
21+
22+
from functools import reduce
23+
24+
25+
def add(x, y):
26+
return x + y
27+
28+
29+
reduce(add, [1, 2, 3, 4, 5]) #15
30+
31+
#把序列[1, 3, 5, 7, 9]变换成整数13579,
32+
33+
from functools import reduce
34+
35+
36+
def fn(x, y):
37+
return x * 10 + y
38+
39+
40+
reduce(fn, [1, 3, 5, 7, 9]) #13579
41+
42+
#一个str2int的函数就是:
43+
from functools import reduce
44+
45+
DIGITS = {
46+
'0': 0,
47+
'1': 1,
48+
'2': 2,
49+
'3': 3,
50+
'4': 4,
51+
'5': 5,
52+
'6': 6,
53+
'7': 7,
54+
'8': 8,
55+
'9': 9
56+
}
57+
58+
59+
def str2int(s):
60+
def fn(x, y):
61+
return x * 10 + y
62+
63+
def char2num(s):
64+
return DIGITS[s]
65+
66+
return reduce(fn, map(char2num, s))
67+
68+
str2int('34678') #34678

函数式编程/高阶函数/sorted.py

Whitespace-only changes.

0 commit comments

Comments
 (0)