python 列表,字典 ,集合推导

列表推导式

L = [x**2 for x in range(11)]
print(L)

'''
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
'''

L1 = [x**2 for x in range(1,11) if x%2==0]
print(L1)
'''
[4, 16, 36, 64, 100]
'''

L2 = [x+y for x in 'abc' for y in 'def']
print(L2)
'''
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
'''

L3 = [[1,2,3],[4,5,6],[7,8,9]]
print([L3[i][2] for i in range(3)])
print([x[-1] for x in L3])
print([x[i] for i,x in enumerate(L3)])

'''
[3, 6, 9]
[3, 6, 9]
[1, 5, 9]
'''

字典推导式

print({x:y for x,y in enumerate('wdfjakg')})

'''
{0: 'w', 1: 'd', 2: 'f', 3: 'j', 4: 'a', 5: 'k', 6: 'g'}
'''

快速更换Key和value

dicts = {0: 'w', 1: 'd', 2: 'f', 3: 'j', 4: 'a', 5: 'k', 6: 'g'}

dict_cg ={v:k for k,v in dicts.items()}

print( dict_cg)
'''
{'w': 0, 'd': 1, 'f': 2, 'j': 3, 'a': 4, 'k': 5, 'g': 6}
'''

集合推导式

strings = ['dff','dffgfg0','dgfgdfadsff']

S = {len(s) for s in strings}
S1 = {x**2 for x in range(1,11) if x%2==0}
print(S,type(S))
print(S1,type(S1))

'''
{11, 3, 7} <class 'set'>
{64, 100, 4, 36, 16} <class 'set'>
    '''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值