[Dynamic Language] Python 列表推导
时间:2010-12-11 来源:※ABeen※
列表推导相当于通过重复调用结果列表的append方法建立相同列表的for循环。
演示:
l = [1,2,3,4,5,6]
result1 = [x+1 for x in l]
相当于以下代码:
result2 = []
for x in l :
result2.append(x+1)
result3 = [x+1 for x in l if x > 3]
相当于以下代码:
result4 = []
for x in l:
if x > 3:
result4.append(x+1)
l2 = [4,5,6]
result5 = [x+y for x in l if x>4 for y in l2 if y>5]
相当于以下代码:
result6 = []
for x in l:
if x > 4:
for y in l2:
if y > 5:
result6.append(x+y)
相关阅读 更多 +