【问题标题】:Unexpected behavior in Python 3: The list contents disappear after printed [duplicate]Python 3 中的意外行为:打印后列表内容消失 [重复]
【发布时间】:2019-11-11 20:11:11
【问题描述】:

我正在学习 Python,在进行一些编码练习时,我复制了一行,结果出乎意料。

def myfunc(x):
    return x*2 
myList = [1,2,3,4,5]
newList = map(myfunc, myList)
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))
print('Using myfunc on the original list: ',myList,' results in: ',list(newList))

我希望看到两次相同的结果,但我得到了这个:

Using myfunc on the original list:  [1, 2, 3, 4, 5]  results in:  [2, 4, 6, 8, 10]
Using myfunc on the original list:  [1, 2, 3, 4, 5]  results in:  []

为什么会发生这种情况以及如何避免?

【问题讨论】:

  • 正如 ForceBru 在下面的答案中所说,newList 是地图生成器,而不是列表。如果您希望 newList 实际上是一个列表,您可以使用 newList = list(map(myfunc, myList)) 这将使事情按您的预期工作。

标签: python-3.x


【解决方案1】:

newList 不是列表。它是一个按需生成数据的生成器,在您使用list(newList) 检索到它保存的所有数据后,它就会耗尽。因此,当您再次调用 list(newList) 时,列表中没有更多数据可放入,所以它仍然是空的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多