Map 对象在 Python 3 中没有 len() [英] Map object has no len() in Python 3

查看:30
本文介绍了Map 对象在 Python 3 中没有 len()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

所以,我移植了其中的大部分内容,但是这一行出现了问题:

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

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

file 函数在 Python 3 中不存在,必须替换为 open.但是,以 data 作为参数的函数会导致异常:

The file function does not exist in Python 3 and has to be replaced with open. But then, a function which gets data as an argument causes an exception:

TypeError: object of type 'map' has no len()

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

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

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

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

推荐答案

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

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

data = list(map(...))

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

And we can do it simply, like this

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

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

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

引自 open 的文档

Quoting from the open's docs,

Python 区分二进制和文本 I/O.打开的文件二进制模式(包括模式参数中的b")将内容返回为没有任何解码的字节对象.

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.

这篇关于Map 对象在 Python 3 中没有 len()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆