`

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

 
  
 


 

  • 大小: 1.2 KB
  • 大小: 1.7 KB
  • 大小: 1.4 KB
  • 大小: 2 KB
  • 大小: 1.2 KB
  • 大小: 1.6 KB
  • 大小: 6.9 KB
分享到:
评论
Global site tag (gtag.js) - Google Analytics