通用的列表解析结构如下:
[expression for target1 in iterable1 [if condition1]
for target1 in iterable2 [if condition2]
for target1 in iterable3 [if condition3]
for target1 in iterable4 [if condition4]
... .... ... .... ... ... ... ... ... ... ... ... ... ... .
for targetN in iterableN [if conditionN]]
例如:
rs = [x + y + z for x in range(7) if x % 2 == 0 for y in range(-10,5) if (y +1) % 3 == 1 for z in [34,43,544,6565] ]
print rs
#output: [25, 34, 535, 6556, 28, 37, 538, 6559, 31, 40, 541, 6562, 34, 43, 544, 6565, 37, 46, 547, 6568, 27, 36, 537, 6558, 30, 39, 540, 6561, 33, 42, 543, 6564, 36, 45, 546, 6567, 39, 48, 549, 6570, 29, 38, 539, 6560, 32, 41, 542, 6563, 35, 44, 545, 6566, 38, 47, 548, 6569, 41, 50, 551, 6572, 31, 40, 541, 6562, 34, 43, 544, 6565, 37, 46, 547, 6568, 40, 49, 550, 6571, 43, 52, 553, 6574]
等价于:
rx = []
for x in range(7):
if x % 2 == 0:
for y in range(-10, 5):
if (y + 1) % 3 == 1:
for z in [34, 43, 544, 6565]:
rx.append(x + y + z)
print rx
测试相等性:
print rs == rx #True