Waarom geeft het volgende script de fout:
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]
Antwoord 1, autoriteit 100%
In Python 3 retourneert map
een itereerbaar object van het type map
, en geen subscriptbare lijst, waarmee je map[i]
. Om een lijstresultaat te forceren, schrijft u
payIntList = list(map(int,payList))
In veel gevallen kunt u uw code echter veel mooier uitschrijven door geen indices te gebruiken. Bijvoorbeeld met lijstbegrippen:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
Antwoord 2, autoriteit 12%
map()
retourneert geen lijst, het retourneert een map
object.
Je moet list(map)
aanroepen als je wilt dat het weer een lijst wordt.
Nog beter,
from itertools import imap
payIntList = list(imap(int, payList))
Het neemt niet veel geheugen in beslag om een tussenobject te maken, het geeft gewoon de ints
door terwijl het ze maakt.
Je kunt ook if choice.lower() == 'n':
doen, zodat je het niet twee keer hoeft te doen.
Python ondersteunt +=
: je kunt desgewenst payIntList[i] += 1000
en numElements += 1
doen.
Als je echt lastig wilt zijn:
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
en/of
for payInt in payIntList:
payInt += 1000
print payInt
Vier spaties is ook het standaard aantal inspringingen in Python.
Antwoord 3
Je hoeft geen bereik te gebruiken voor dit probleem in pypy3 of python3, dus het is eigenlijk minder code..
for i in payIntList: print ( i + 1000 )
en komt toevallig overeen met de opmerking van RustyTom in de bovenstaande oplossing van PhiHag. Opmerking: kan niet verwijzen naar een kaart met behulp van array-haakjes [] in pypy3 of python3, anders geeft het dezelfde fout.
payIntList[i]
Kaartref heeft de fout veroorzaakt.