Python 3 - TypeError: 'map'对象不可被索引
Python 3 - TypeError: 'map'对象不可被索引
我目前正在我的代码中运行这段代码作为我的输入/输出流 - 我得到以下错误TypeError: 'map' object is not subscriptable for the print (bytest[:10])。在Python 3中,正确的运行方式是什么?
with open("/bin/ls", "rb") as fin: #rb as text file and location buf = fin.read() bytes = map(ord, buf) print (bytes[:10]) saveFile = open('exampleFile.txt', 'w') saveFile.write(bytes) saveFile.close()
在Python 3中,map
函数返回一个生成器。如果想要解决这个问题,可以尝试先将其转换成列表。
以下是一段代码示例:
with open("/bin/ls", "rb") as fin: buf = fin.read() bytes = list(map(ord, buf)) print (bytes[:10]) saveFile = open('exampleFile.txt', 'w') saveFile.write(bytes) saveFile.close()
如果你认为这段代码看起来很丑陋,你可以用列表生成器来替代:
bytes = [ord(b) for b in buf]
另外,你还可以使用itertools.islice
来解决这个问题。如果你只需要一次读取特定的片段,这可能是更好的选择。
希望以上的内容对你有帮助!