0

我正在学习 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:  []

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

4

1 回答 1

4

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

于 2019-11-11T20:22:45.653 回答