Skip to content

Commit 3cb96db

Browse files
committed
更新md
更新md
1 parent efe1beb commit 3cb96db

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

python_basic/main.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@
1919
17. [json文件处理](json文件处理.md)
2020
18. [Excel文件处理](Excel文件处理.md)
2121
19. [深拷贝与浅拷贝](深拷贝与浅拷贝.md)
22+
20. [列表推导式,map,filter,reduce](列表推导式.md)

python_basic/列表推导式.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#### map(__func, __iter)
2+
map会将一个函数映射到一个输入列表的所有元素上.
3+
```python
4+
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
5+
list_x_multi_two = map(lambda x: 2 * x, list_x)
6+
# <map object at 0x000001E696035DA0>
7+
print(list_x_multi_two)
8+
# [2, 4, 6, 8, 10, 12, 14, 16]
9+
print(list(list_x_multi_two))
10+
```
11+
12+
#### filter(__func, __iter)
13+
过滤列表中的元素
14+
```python
15+
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
16+
list_x_more_than_5 = filter(lambda x: x > 5, list_x)
17+
# <filter object at 0x000001E69601D630>
18+
print(list_x_more_than_5)
19+
# [6, 7, 8]
20+
print(list(list_x_more_than_5))
21+
```
22+
23+
#### 列表推导式部分情况可以替代map,filter函数
24+
```python
25+
# [2, 4, 6, 8, 10, 12, 14, 16]
26+
print([x*2 for x in list_x])
27+
28+
# [6, 7, 8]
29+
print([x for x in list_x if x > 5])
30+
```
31+
32+
#### reduce(func, sequence)
33+
对参数序列中元素进行累计计算。用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
34+
```python
35+
from functools import reduce
36+
37+
sum_ = reduce((lambda x, y:x+y), list_x)
38+
print(sum_) # 36
39+
```

0 commit comments

Comments
 (0)