Python 地图对象不可订阅

新手上路,请多包涵

为什么下面的脚本会报错:

payIntList[i] = payIntList[i] + 1000 TypeError: 'map' object is not subscriptable

 payList = []
numElements = 0

while True:
        payValue = raw_input("Enter the pay amount: ")
        numElements = numElements + 1
        payList.append(payValue)
        choice = raw_input("Do you wish to continue(y/n)?")
        if choice == 'n' or choice == 'N':
                         break

payIntList = map(int,payList)

for i in range(numElements):
         payIntList[i] = payIntList[i] + 1000
         print payIntList[i]

原文由 station 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 720
2 个回答

在 Python 3 中, map 返回类型为 map 的可迭代对象,而不是可订阅列表,它允许您编写 map[i] 要强制列表结果,请写

payIntList = list(map(int,payList))

但是,在许多情况下,您可以通过不使用索引来更好地编写代码。例如,使用 列表理解

 payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

原文由 phihag 发布,翻译遵循 CC BY-SA 3.0 许可协议

map() 不返回列表,它返回一个 map 对象。

如果你想让它再次成为一个列表,你需要调用 list(map)

更好的是,

 from itertools import imap
payIntList = list(imap(int, payList))

不会占用大量内存来创建中间对象,它只会在创建它们时将 ints 传递出去。

另外,你可以做 if choice.lower() == 'n': 所以你不必做两次。

Python 支持 += :你可以做 payIntList[i] += 1000numElements += 1 如果你愿意的话。

如果你真的想变得棘手:

 from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

和/或

for payInt in payIntList:
    payInt += 1000
    print payInt

此外,四个空格是 Python 中的标准缩进量。

原文由 agf 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题