Python:使用地图功能 [英] Python : Using the map function
本文介绍了Python:使用地图功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 map
函数时遇到了麻烦.当我要打印创建的列表时,解释器显示指针:
I'm having trouble with the map
function. When I want to print the created list, the interpreter shows the pointer:
>>> squares = map(lambda x: x**2, range(10))
>>> print(squares)
<map object at 0x0000000002A086A0>
出什么问题了?
推荐答案
问题是未创建列表. map
返回特定类型的生成器,Python 3不是列表(而是一个映射对象",如您所见).你可以尝试
The problem is that a list is not created. map
returns a specific type of generator in Python 3 that is not a list (but rather a 'map object', as you can see). You can try
print(list(squares))
或者只是使用列表理解来首先获取列表(无论如何在这里似乎效果更好):
Or just use a list comprehension to obtain a list in the first place (which seems to work better here anyway):
squares = [x**2 for x in range(10)]
map
used to return a list in Python 2.x, and the change that was made in Python 3 is described in this section of the documentation:
map()
和filter()
返回迭代器.如果您确实需要列表,可以使用例如快速修复的方法.list(map(...))
,但是更好的解决方案通常是使用列表理解功能(尤其是当原始代码使用lambda
时),或者重写代码,因此根本不需要列表.为函数的副作用而调用map()
尤其棘手;正确的转换是使用常规的for
循环(因为创建列表只是浪费).
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:使用地图功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文