我在使用 map
函数时遇到问题。当我想打印创建的列表时,解释器显示指针:
>>> squares = map(lambda x: x**2, range(10))
>>> print(squares)
<map object at 0x0000000002A086A0>
问题是什么?
最佳答案
问题是没有创建列表。 map
返回特定类型的 iterator在 Python 3 中,它不是一个列表(而是一个“ map 对象”,如您所见)。你可以试试
print(list(squares))
或者首先使用列表理解来获取列表(无论如何,这似乎在这里工作得更好):
squares = [x**2 for x in range(10)]
map
用于在 Python 2.x 中返回一个列表,在 Python 3 中所做的更改在 this 中进行了描述。文档部分:
map()
andfilter()
return iterators. If you really need a list, a quick fix is e.g.list(map(...))
, but a better fix is often to use a list comprehension (especially when the original code useslambda
), or rewriting the code so it doesn’t need a list at all. Particularly tricky ismap()
invoked for the side effects of the function; the correct transformation is to use a regularfor
loop (since creating a list would just be wasteful).
关于python - 使用 map 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18087544/