使用生成器展平嵌套列表

时间:2019-04-29 12:11:05

标签: python generator

我在 Beginning Python From Novice to Professional(Third Exdition)

这本书的 9.7.1创建生成器中编写了示例代码。

但是我没有输出书中应该显示的内容。

书中的示例:

def flatten(nested):
    for sub in nested:
        for element in nested:
            yield element

nested = [[1,2],[3,4],[5]]

for num in flatten(nested):
    print(num)

书中的输出:

 1
 2
 3
 4
 5

我在python 3.7.2中的输出:

[1, 2]
[3, 4]
[5]
[1, 2]
[3, 4]
[5]
[1, 2]
[3, 4]
[5]

我的python有什么问题?

1 个答案:

答案 0 :(得分:3)

第三行应为for element in sub:

def flatten(nested):
    for sub in nested:
        for element in sub:  # typo was here
            yield element

nested = [[1,2],[3,4],[5]]

for num in flatten(nested):
    print(num)