我理解如何使用简单的列表推导式,例如:
[x*2 for x in range(5)] # returns [0,2,4,6,8]
而且我也理解嵌套的列表推导式是如何工作的:
w_list = ["i_have_a_doubt", "with_the","nested_lists_comprehensions"]
# returns the list of strings without underscore and capitalized
print [replaced.title() for replaced in [el.replace("_"," ")for el in w_list]]
所以,当我试图做这件事时
l1 = [100,200,300]
l2 = [0,1,2]
[x + y for x in l2 for y in l1 ]
我原本期待这个:
[100,201,302]
但是我得到了这个:
[100,200,300,101,201,301,102,202,302]
所以我找到了一个更好的解决问题的方法,它给了我想要的结果。
[x + y for x,y in zip(l1,l2)]
但我不理解第一段代码返回9个元素的原因。