Skip to content

Commit 2386f3b

Browse files
authored
练习高级特性的列表生成式
1 parent 6ea5ada commit 2386f3b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

test5.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# 练习列表生成式,这个很好用,越用越爽
2+
3+
4+
l = [x for x in range(10)]
5+
print(l)
6+
# 还可以加条件来筛选元素,这里筛选偶数
7+
l = [x for x in range(10) if x % 2 == 0]
8+
print(l)
9+
# 对两个列表生成一个也可以,生成全排列
10+
l = [x + y for x in 'XYZ' for y in 'abc']
11+
print(l)
12+
# 也可以生成字典
13+
d = {x:y for x in 'xyz' for y in 'ABC'}
14+
print(d)
15+
16+
17+
# 作业:将列表的字符串的大写改成小写,不是字符串的就去掉
18+
L1 = ['Hello', 'World', 18, 'Apple', None]
19+
print(L1)
20+
L2 = [s.lower() for s in L1 if isinstance(s,str)]
21+
print(L2)
22+

0 commit comments

Comments
 (0)