python之列表推导式的应用

# 大于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'}
---




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值