List.extend()无法在Python中按预期工作

List.extend() is not working as expected in Python

本问题已经有最佳答案,请猛点这里访问。

我有一个列表queue和一个迭代器对象neighbors,我要将其元素附加到列表中。

1
2
3
4
5
queue = [1]
neighbor = T.neighbors(1) #neighbor is a <dict_keyiterator at 0x16843d03368>
print(list(neighbor)) #Output: [2, 3]
queue.extend([n for n in neighbor])
print(queue)

输出:

1
[1]

预期产量:

1
[1, 2, 3]

怎么了?


list构造函数中使用迭代器neighbor进行打印时,您已经用尽了它,因此在下一行的列表理解中它变为空。

将转换后的列表存储在一个变量中,以便您既可以打印它也可以在列表理解中使用它:

1
2
3
4
5
6
queue = [1]
neighbor = T.neighbors(1) #neighbor is a <dict_keyiterator at 0x16843d03368>
neighbors = list(neighbor)
print(neighbors) #Output: [2, 3]
queue.extend([n for n in neighbors])
print(queue)


您已经消耗了迭代器:

1
print(list(neighbor))

把那条线拿出来。