python - 使用 map 功能

标签 python dictionary

我在使用 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() and filter() 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 uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

关于python - 使用 map 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18087544/

相关文章:

python - 将 Pandas 数据框中的列移动到大型数据框中的最后一列的最佳方法

python - 如何使用 RE 查找字符串中的多个平衡大小匹配项?

python - 如何在OpenERP上实现抽象类?

python - 在子类python中调用基类方法

javascript - 如何在 JSX 代码中打印数组的所有元素(作为父状态的 props 传递)?

c++ - const引用传递的参数在函数中是否完全充当了const类型的变量?

python - 为从 dict 创建的 pandas 数据框设置名称

python - PyQt5多线程

python - Rpy2:如何将字典列表转换为 R 数据框

将键与单个字典的公共(public)值合并的 Pythonic 方法