Python映射对象不可下标

发布于 2021-01-29 19:34:51

为什么以下脚本会给出错误:

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]
关注者
0
被浏览
77
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    payIntList = list(map(int,payList))
    

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

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看