Python列表生成式

原创转载请注明出处:http://agilestyle.iteye.com/blog/2329193

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(range(1, 11)))

Console Output

# [1x1, 2x2, 3x3, ..., 10x10]
l1 = [x * x for x in range(1, 11)]
print(l1)

Console Output

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

Console Output

 

# ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
l3 = [m + n for m in 'ABC' for n in 'XYZ']
print(l3)

Console Output

 

d = {'a': '1', 'b': '2', 'c': '3'}
l4 = [k + '=' + v for k, v in d.items()]
print(l4)

Console Output

l5 = [str.lower() for str in ['iMac', 'iPhone', 'iPad', 'iPod']]
print(l5)

Console Output

 

列出C盘Program Files目录下的所有目录

import os

directory = [d for d in os.listdir('C:/Program Files')]
print(directory)

Console Output

 
  
 


 

猜你喜欢

转载自agilestyle.iteye.com/blog/2329193
今日推荐