Python中的推导式

1. 列表(list)推导式

基本格式:[x for x in data if condition]

[x for x in range(50) if x%2!=0]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

2.字典(dict)推导式

基本格式:{x:condition for x in data}

{x:x%2!=0 for x in range(50)}
{0: False, 1: True, 2: False, 3: True, 4: False, 5: True, 6: False, 7: True, 8: False, 9: True, 10: False, 11: True, 12: False, 13: True, 14: False, 15: True, 16: False, 17: True, 18: False, 19: True, 20: False, 21: True, 22: False, 23: True, 24: False, 25: True, 26: False, 27: True, 28: False, 29: True, 30: False, 31: True, 32: False, 33: True, 34: False, 35: True, 36: False, 37: True, 38: False, 39: True, 40: False, 41: True, 42: False, 43: True, 44: False, 45: True, 46: False, 47: True, 48: False, 49: True}

3.集合(set)推导式

基本格式:{x for x in data if condition}

{x for x in [1,1,1,2,2,3,4,5,5,6,7,8,8,9,9,10] if x%2!=0}
{1, 3, 5, 7, 9}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值