簡體   English   中英

Nested list comprehension with two lists

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM