[英]Nested list comprehension with two lists
I understand how the simple list comprehension works eg.:
[x*2 for x in range(5)] # returns [0,2,4,6,8]
and also I understand how the nested list comprehesion works:
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]]
so, when I tried do this
l1 = [100,200,300]
l2 = [0,1,2]
[x + y for x in l2 for y in l1 ]
I expected this:
[100,201,302]
but I got this:
[100,200,300,101,201,301,102,202,302]
so I got a better way solve the problem, which gave me what I want
[x + y for x,y in zip(l1,l2)]
but I didn't understood the return of 9 elements on the first code
它有 9 个数字的原因是因为 python 对待
[x + y for x in l2 for y in l1 ]
类似于
for x in l2: for y in l1: x + y
即,它是一个嵌套循环
列表推导等同于 for 循环。 因此, [x + y for x in l2 for y in l1 ]
将变为:
new_list = [] for x in l2: for y in l1: new_list.append(x + y)
而zip
返回包含每个列表中一个元素的元组。 因此[x + y for x,y in zip(l1,l2)]
等价于:
new_list = [] assert len(l1) == len(l2) for index in xrange(len(l1)): new_list.append(l1[index] + l2[index])
以上答案足以解决您的问题,但我想为您提供一个列表理解解决方案以供参考(因为那是您的初始代码以及您想要理解的内容)。
假设两个列表的长度相同,您可以这样做:
[l1[i] + l2[i] for i in range(0, len(l1))]
[x + y for x in l2 for y in l1 ]
相当于:
lis = [] for x in l: for y in l1: lis.append(x+y)
因此,对于l
的每个元素,您一次又一次地迭代l2
,因为l
有 3 个元素,而l1
有元素,所以总循环等于 9( len(l)*len(l1)
)。
这个序列
res = [x + y for x in l2 for y in l1 ]
相当于
res =[] for x in l2: for y in l1: res.append(x+y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.