Python地图对象不可订阅

sta*_*ion 59 python python-3.x

为什么以下脚本会出错:

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]
Run Code Online (Sandbox Code Playgroud)

phi*_*hag 103

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

payIntList = list(map(int,payList))
Run Code Online (Sandbox Code Playgroud)

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

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是正确的,但理想情况下,您不会将地图转换为列表以用于此类用例.地图已经可迭代,与列表相比,迭代速度似乎要快一个数量级.因此,您不仅不需要索引,也不需要列表.更干净的代码是,因为payIntList已经是一个地图,`for for in payIntList:print(i + 1000)` (3认同)

agf*_*agf 14

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

list(map)如果您希望它再次成为列表,则需要调用.

更好的是,

from itertools import imap
payIntList = list(imap(int, payList))
Run Code Online (Sandbox Code Playgroud)

不会占用一堆内存创建一个中间对象,它只会在ints创建它们时传递掉.

此外,您可以这样做if choice.lower() == 'n':,您不必两次.

Python支持+=:你可以做payIntList[i] += 1000,numElements += 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
Run Code Online (Sandbox Code Playgroud)

和/或

for payInt in payIntList:
    payInt += 1000
    print payInt
Run Code Online (Sandbox Code Playgroud)

另外,四个空格是Python中的标准缩进量.