【问题标题】:List.extend() is not working as expected in Python [duplicate]List.extend() 在 Python 中没有按预期工作 [重复]
【发布时间】:2019-02-24 10:39:10
【问题描述】:

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

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, 2, 3]

出了什么问题?

【问题讨论】:

  • 试试:queue.extend(list(neighbor))
  • 那行不通。

标签: python


【解决方案1】:

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

将转换后的列表存储在一个变量中,以便您可以打印它并在列表推导中使用它:

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)

【讨论】:

  • 或者只是queue.extend(neighbors) 就可以了
  • 太棒了!这么微小的错误。非常感谢。
【解决方案2】:

您已经使用了迭代器:

print(list(neighbor))

去掉那条线。

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2012-11-01
    • 2011-12-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2016-11-09
    • 2021-08-14
    • 2013-03-25
    相关资源
    最近更新 更多