Map对象在Python 3.3中没有len() [英] Map object has no len() in Python 3.3
问题描述
所以,我有这个python工具被其他人刷新某个微控制器,但他已经写了他的工具为python 2.6,我使用的是python 3.3。
所以,大部分都被移植,但是这行:
data = map(lambda c:ord(c) file(args [0],'rb')。read())
正在发生问题。 文件
函数在Python 3.3中不存在,必须用打开
替换。但是,一个获取数据
作为参数的函数会导致一个异常,指出一个映射对象不可迭代
。 / p>
但是我到目前为止在文档中看到的是, map
必须将迭代类型加入到一个大的迭代中,我是否缺少某些东西?
我需要做什么才能将其移植到Python 3.3?
在Python 3.3中, map
返回一个迭代器,如果你的函数需要一个列表,必须被显式转换,像这样
data = list(map(...))
我们可以这样做,就像这样
with open(args [0] ,rb)as input_file:
data = list(input_file.read())
rb
是指以二进制模式读取。所以,它实际上返回字节。所以,我们只需将它们转换成一个列表。
从 打开
的文档,
Python区分二进制和文本I / O。文件以
二进制模式打开(包括模式参数中的'b')返回内容为
字节对象,无需任何解码。
So, I have this python tool wirtten by someone else to flash a certain microcontroller, but he has written his tool for python 2.6 and I am using python 3.3.
So, most of it I got ported, but this line:
data = map(lambda c: ord(c), file(args[0], 'rb').read())
is making problems. The file
function does not exist in Python 3.3 and has to be replaced with open
. But then, a function which gets data
as an argument causes an exception stating that a map object is not iterable
.
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?
What do I have to do to port this to Python 3.3?
In Python 3.3, map
returns an iterator, if your function expects a list, that 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
refers to read in binary mode. So, it actually returns the bytes. So, we just have to convert them to a list.
Quoting from the 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.
这篇关于Map对象在Python 3.3中没有len()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!