1. 程式人生 > >列表:推導列表

列表:推導列表

推導列表

單層循環

>> [x*x for x in xrange(1,10)]
[1, 4, 9, 16, 25, 36, 49, 64, 81]

單層循環,帶if語句

>> [x*x for x in xrange(1,10) if x%2 == 0]
[4, 16, 36, 64]

雙層循環

>> [m+n for m in "ABC" for n in "XYZ"]
[‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]

>> [x+y for x in [1,2,3] for y in [9,8,7]]

[10, 9, 8, 11, 10, 9, 12, 11, 10]

雙層循環帶if語句

>> [m+n for m in "ABC" for n in "XYZ" if m == "A" and n == "X"]
[‘AX‘]

>> [x+y for x in [1,2,3] for y in [9,8,7] if x==1 and y==9]
[10]
>>

for 循環可以同時使用兩個或多個變量
比如遍歷字典

>> d = {1:"a",2:"b",3:"c"}

>> [str(k) + "=" + v for k,v in d.items()]
[‘1=a‘, ‘2=b‘, ‘3=c‘]

列表:推導列表