相关疑难解决方法(0)

嵌套列表理解有两个列表

我理解简单列表理解是如何工作的,例如:

[x*2 for x in range(5)] # returns [0,2,4,6,8]
Run Code Online (Sandbox Code Playgroud)

而且我也理解嵌套列表comprehesion的工作原理:

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]]
Run Code Online (Sandbox Code Playgroud)

所以,当我尝试这样做的时候

l1 = [100,200,300]
l2 = [0,1,2]
[x + y for x in l2 for y in l1 ]
Run Code Online (Sandbox Code Playgroud)

我期待这个:

[101,202,303]
Run Code Online (Sandbox Code Playgroud)

但我得到了这个:

[100,200,300,101,201,301,102,202,302]
Run Code Online (Sandbox Code Playgroud)

所以我有一个更好的方法解决问题,这给了我想要的东西

[x + y for x,y in zip(l1,l2)]
Run Code Online (Sandbox Code Playgroud)

但我不理解第一个代码上9个元素的返回

python nested list-comprehension

37
推荐指数
3
解决办法
5万
查看次数

标签 统计

list-comprehension ×1

nested ×1

python ×1