List.extend() is not working as expected in Python
本问题已经有最佳答案,请猛点这里访问。
我有一个列表
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] |
怎么了?
在
将转换后的列表存储在一个变量中,以便您既可以打印它也可以在列表理解中使用它:
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)) |
把那条线拿出来。