【问题标题】:Python 3 - TypeError: 'map' object is not subscriptable [duplicate]Python 3 - TypeError:'map'对象不可下标[重复]
【发布时间】:2017-05-08 12:12:38
【问题描述】:

我目前正在将此作为 i/o 流的一段代码运行 - 我收到以下错误 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


    【解决方案1】:

    在 Python 3 中,map 返回一个生成器。尝试先从它创建一个list

    with open("/bin/ls", "rb") as fin: #rb as text file and location 
      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 f in buf]
    

    【讨论】:

    • 你可以使用itertools.islice
    • @PeterWood 是的,如果您只需要阅读特定切片一次,那可能会更好。
    猜你喜欢
    • 2015-12-18
    • 1970-01-01
    • 2021-11-29
    • 2018-03-08
    • 2014-02-26
    • 2015-02-27
    • 1970-01-01
    • 2017-01-22
    • 2021-02-19
    相关资源
    最近更新 更多