python3 列表/字典/集合推导式

 
 
'''列表推导式[结果 fox循环 if语句]'''
lst = ["Python周末%s期" % i for i in range(1, 27) if i%2 == 0]
print(lst)

结果:
['Python周末2期', 'Python周末4期', 'Python周末6期', 'Python周末8期', 'Python周末10期', 'Python周末12期', 'Python周末14期', 'Python周末16期', 'Python周末18期', 'Python周末20期', 'Python周末22期', 'Python周末24期', 'Python周末26期']

'''列表生成式可以快速的创建一个列表'''
lst = [i*i for i in range(10)]
print(lst)
lst2 = [i if i < 5 else i*i for i in range(10)]
print(lst2)
lst3 = [i*i for i in range(10) if i >= 5]
print(lst3)
lst4 = [i for i in ["apple", "orange", "banana", "pear"] if i.endswith("e")]
print(lst4)


'''使用列表推导式得到[1, 4, 9, 16, 25, 36]'''
print([i*i for i in range(1, 7)])

'''在[3,6,9]的基础上推到出[[1,2,3], [4,5,6],[7,8,9]]'''
print([[i-2, i-1, i] for i in [3, 6, 9]])

返回结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 2, 3, 4, 25, 36, 49, 64, 81]
[25, 36, 49, 64, 81]
['apple', 'orange']
[1, 4, 9, 16, 25, 36]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

'''字典推导式{key:value fox循环 if语句}'''
lst = ["apple", "orange", "banana"]
dic = {k:v for k,v in
enumerate(lst)}
print(dic)

返回结果:
{0: 'apple', 1: 'orange', 2: 'banana'}
 
'''集合推导式{key for循环 if语句}'''
lst = [3, 5, 1, 5, 2, 1, 7]
s = {i for i in lst}
print(s)

返回结果:
{1, 2, 3, 5, 7}
 

转载于:https://www.cnblogs.com/lilyxiaoyy/p/10762281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值