"map"类型的对象在Python 3中没有len()

Son*_*ius 36 python variable-length python-3.x

我有Python 3的问题.我得到了Python 2.7代码,目前我正在尝试更新它.我收到错误:

TypeError:'map'类型的对象没有len()

在这一部分:

str(len(seed_candidates))
Run Code Online (Sandbox Code Playgroud)

在我像这样初始化之前:

seed_candidates = map(modify_word, wordlist)
Run Code Online (Sandbox Code Playgroud)

那么,有人可以解释一下我必须做什么吗?

(编辑:以前这个代码示例是错误的,因为它使用set而不是map.它现在已经更新.)

Ter*_*ryA 63

在Python 3中,map返回一个地图对象而不是list:

>>> L = map(str, range(10))
>>> print(L)
<map object at 0x101bda358>
>>> print(len(L))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'map' has no len()
Run Code Online (Sandbox Code Playgroud)

您可以将其转换为列表,然后从那里获取长度:

>>> print(len(list(L)))
10
Run Code Online (Sandbox Code Playgroud)

  • 我认为这有一个规范的问题/答案.上述问题是重复的. (2认同)
  • 我认为 list(L) 将使迭代器运行到最后,这将使该迭代器不再有用(除非您故意重现该迭代器) (2认同)

the*_*pen 6

虽然接受的答案可能适用于 OP,但这里有一些东西需要学习,因为有时即使将 OPmap(modify_word, wordlist)放入列表并使用len(list(map(modify_word, wordlist))). 你不能,因为有时长度是无限的

例如,让我们考虑以下惰性计算所有自然数的生成器:

def naturals():
    num = 0
    while True:
        yield num
        num +=1
Run Code Online (Sandbox Code Playgroud)

假设我想得到每个的平方,也就是说,

doubles = map(lambda x: x**2, naturals())
Run Code Online (Sandbox Code Playgroud)

请注意,这是对 map 函数的完全合法使用,并且会起作用,并且允许您对doubles变量使用 next() 函数:

>>> doubles = map(lambda x: x**2, naturals())
>>> next(doubles)
0
>>> next(doubles)
1
>>> next(doubles)
4
>>> next(doubles)
9
...
Run Code Online (Sandbox Code Playgroud)

但是,如果我们尝试将其转换为列表呢?显然 python 不知道我们是否正在尝试遍历一个永无止境的迭代器。因此,如果我们尝试将这个 mapObject 的一个实例转换为一个列表,python 将继续尝试并陷入无限循环。

因此,当您转换为列表时,您应该首先确保您知道您的地图对象确实会产生有限数量的元素。