【发布时间】: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