嵌套列表理解/合并嵌套列表 [英] Nested list comprehension / merging nested lists

查看:95
本文介绍了嵌套列表理解/合并嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解嵌套列表理解结构时遇到问题.

I have a problem understanding a nested list comprehension structure.

我有一个清单

>>> test
[[1, 2, 3], [4, 5], [6, 7, 8]]

如果我愿意

t2=[]
for x in test:
    for y in x:
        t2.append(y)

然后返回

>>> t2
[1, 2, 3, 4, 5, 6, 7, 8]

这正是我想要的.但是为什么我不能

which is exactly what I want. But WHY can't I do

t3=[y for y in x for x in test]

这给了我

>>> t3
[6, 6, 6, 7, 7, 7, 8, 8, 8]

有人可以向我解释为什么t3与t2不同吗?我如何编写一个列表理解表达式,使其与t2相同?非常感谢您的帮助!

Can anybody explain to me why t3 is not the same as t2? How ca I write a list comprehension expression that gives me the same as t2? Thank you very much for your help!

推荐答案

列表理解中的for ... in ...子句的排列顺序必须与正常的for循环相同:

The for ... in ... clauses inside a list comprehension need to go in the same order as if they were normal for-loops:

>>> test = [[1, 2, 3], [4, 5], [6, 7, 8]]
>>> t3 = [y for x in test for y in x]
>>> t3
[1, 2, 3, 4, 5, 6, 7, 8]
>>>

这篇关于嵌套列表理解/合并嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆