推导式的基本结构:
[表达式 for 可迭代对象 if 判断条件]
生成列表:
print [ x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8]
生成set:
print {x for x in range(10) if x % 2 == 1}
set([1, 3, 9, 5, 7])
生成字典:
print {x:x**2 for x in range(10) if x % 2 == 0}
{0: 0, 8: 64, 2: 4, 4: 16, 6: 36}
双层循环:
>>> print [x + y for x in 'ABC' for y in '234']
['A2', 'A3', 'A4', 'B2', 'B3', 'B4', 'C2', 'C3', 'C4']
双变量:
d = {'x':'A','y':'B','z':'C'}
[x + '=' + y for x,y in d.items()]
['y=B', 'x=A', 'z=C']
表达式可以比较复杂
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L if isinstance(s, str)]
['hello', 'world', 'apple']