1. 程式人生 > >python 列表,字典 ,集合推導

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'>
    '''