Python 地图对象不可下标 [英] Python map object is not subscriptable

查看:63
本文介绍了Python 地图对象不可下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the following script give the error:

payIntList[i] = payIntList[i] + 1000
类型错误:地图"对象不可下标

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].要强制列出结果,请编写

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

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

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

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

这篇关于Python 地图对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆