为什么以下脚本会给出错误:
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]
在Python 3中,map返回类型为的可迭代对象map,而不是可下标的列表,该列表允许您编写map[i]。要强制列出结果,请写
map
map[i]
payIntList = list(map(int,payList))
但是,在许多情况下,您可以不使用索引来更好地编写代码。例如,使用列表推导:
payIntList = [pi + 1000 for pi in payList] for pi in payIntList: print(pi)