# 大于3的数
number = [1,2,3,5,6,7,8,9,0]
result = [i for i in number if i > 3]
print(result)
---
[5, 6, 7, 8, 9]
---
result = [i+1 for i in number if i > 3]
print(result)
---
[5, 6, 7, 8, 9]
---
# 1-100之间被3和5整除的数
newlist = [i for i in range(0,101) if i % 3 ==0 and i % 5 == 0]
print(newlist)
---
[0, 15, 30, 45, 60, 75, 90]
---
# 列表中放进去元组
newlist = [(x,y) for x in range(0,5) if x%2 == 0 for y in range(0,10) if y % 2 != 0]
print(newlist)
---
[(0, 1), (0, 3), (0, 5), (0, 7), (0, 9), (2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (4, 1), (4, 3), (4, 5), (4, 7), (4, 9)]
---
ss = []
for i in range(0,5):
if i%2 == 0:
for j in range(0,10):
if j % 2!=0:
ss.append((i,j))
print(ss)
---
[(0, 1), (0, 3), (0, 5), (0, 7), (0, 9), (2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (4, 1), (4, 3), (4, 5), (4, 7), (4, 9)]
---
# 字典推导,if else 放前面
dict1 = {'name':'tom','score':22}
dict2 = {'name':'jack','score':20}
dict3 = {'name':'lily','score':18}
dict4 = {'name':'lucy','score':16}
list1 = [dict1,dict2,dict3,dict4,]
newlist = [score['score']+2 if score['score'] >= 20 else score['score']-20 for score in list1]
print(newlist)
---
[24, 22, -2, -4]
---
# 字典推导式
dict1 = {'a':'A','b':'B','c':'C','d':'C'}
newdict = {value:key for key ,value in dict1.items()}
print(newdict)
---
{'A': 'a', 'B': 'b', 'C': 'd'}
---
python之列表推导式的应用
最新推荐文章于 2023-05-29 00:45:00 发布