Map 对象在 Python 3 中没有 len()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21572840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:10:28  来源:igfitidea点击:

Map object has no len() in Python 3

pythonpython-3.x

提问by user3219624

I have this Python tool written by someone else to flash a certain microcontroller, but he has written this tool for Python 2.6 and I am using Python 3.3.

我有其他人编写的这个 Python 工具来刷新某个微控制器,但他为 Python 2.6 编写了这个工具,我使用的是 Python 3.3。

So, most of it I got ported, but this line is making problems:

所以,大部分我都被移植了,但这条线正在制造问题:

data = map(lambda c: ord(c), file(args[0], 'rb').read()) 

The filefunction does not exist in Python 3 and has to be replaced with open. But then, a function which gets dataas an argument causes an exception: “TypeError: object of type 'map' has no len()”.

file函数在 Python 3 中不存在,必须替换为open. 但是,data作为参数获取的函数会导致异常:“TypeError: object of type 'map' has no len()”

But what I see so far in the documentation is, that maphas to join iterable types to one big iterable, am I missing something?

但是到目前为止我在文档中看到的是,map必须将可迭代类型加入一个大的可迭代类型,我是否遗漏了什么?

What do I have to do to port this to Python 3?

我需要做什么才能将它移植到 Python 3?

采纳答案by thefourtheye

In Python 3, mapreturns an iterator. If your function expects a list, the iterator has to be explicitly converted, like this:

在 Python 3 中,map返回一个迭代器。如果您的函数需要一个列表,则必须显式转换迭代器,如下所示:

data = list(map(...))

And we can do it simply, like this

我们可以简单地做到这一点,就像这样

with open(args[0], "rb") as input_file:
    data = list(input_file.read())

rbrefers to read in binary mode. So, it actually returns the bytes. So, we just have to convert them to a list.

rb指以二进制方式读取。所以,它实际上返回字节。因此,我们只需要将它们转换为列表。

Quoting from the open's docs,

引自open's docs,

Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.

Python 区分二进制和文本 I/O。以二进制模式打开的文件(包括 mode 参数中的“b”)将内容作为字节对象返回,无需任何解码。