¿Por qué el siguiente script da el error?
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
python-3.x
estación
fuente
fuente

payIntList = [int(x) + 1000 for x in payList]; print(*payIntList, sep='\n')(ofor x in payIntList: print xen Python 2.x dondeprintno es una función) sin perder legibilidad (posiblemente, es aún más legible).Respuestas:
En Python 3,
mapdevuelve un objeto iterable de tipomap, y no una lista subcriptible, lo que le permitiría escribirmap[i]. Para forzar un resultado de lista, escribaSin embargo, en muchos casos, puede escribir su código de una manera más agradable si no usa índices. Por ejemplo, con listas por comprensión :
payIntList = [pi + 1000 for pi in payList] for pi in payIntList: print(pi)fuente
for i in payIntList: print(i + 1000)map()no devuelve una lista, devuelve unmapobjeto.Debes llamar
list(map)si quieres que vuelva a ser una lista.Aun mejor,
from itertools import imap payIntList = list(imap(int, payList))No ocupará un montón de memoria creando un objeto intermedio, simplemente lo pasará
intsa medida que lo crea.Además, puede hacerlo
if choice.lower() == 'n':para no tener que hacerlo dos veces.Soportes de Python
+=: puedes hacerlopayIntList[i] += 1000ynumElements += 1si quieres.Si realmente quieres ser complicado:
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': breaky / o
for payInt in payIntList: payInt += 1000 print payIntAdemás, cuatro espacios es la cantidad de sangría estándar en Python.
fuente
listalrededor de un iterador elimina esa ventaja!list(map(...)), crea unmap, luego crea unlist, luego borra elmap, por lo que durante un tiempo ambos están en la memoria a la vez. Cuando lo haces,list(imap(...))este no es el caso. Por eso dije "tomar memoria con un objeto intermedio "list(map(...))es redundante, porque - como dice la documentación , "el resultado [demap] es siempre una lista".