Python 3.4 TypeError: argument of type 'int' is not iterable

时间:2015-10-30 21:49:41

标签: python arrays

I have an array where each position in the array represents a parking spot. The value of each position in the array (or parking lot) represents what is in the parking spot (car, motorcycle, etc.). The showSpots function should show all of the spots a certain vehicle is in. For example, showSpots(CAR) (where CAR = 1) should show all of the spots (or positions in the array) that hold the value 1.

However, when I run the code, I get a 'TypeError: argument of type 'int' is not iterable' on the line 'if holder in parkingLot[x]:'

Why am I getting this error, and how do I fix it?

My code:

from random import *

parkingLot = [0, 1, 0, 2, 0, 0, 1]

EMPTY = 0
CAR = 1
MOTORCYCLE = 2

def showSpots(holder):
    for x in range(0, 6):
        if holder in parkingLot[x]:
            print(x)

def main():
    print("There are cars in lots:")
    showSpots(CAR)
    print("There are motorcycles in lots:")
    showSpots(MOTORCYCLE)

main()

4 个答案:

答案 0 :(得分:5)

I think you want if holder == parkingLot[x]:. By doing in, Python is trying to iterate through parkingLot[x] and check if holder is in it. Obviously, since you can't do list(1), then an error is raised.

答案 1 :(得分:1)

parkingLot[x] is a single integer, but in expects a sequence (i.e. a list, a tuple, a dictionary, etc.)

答案 2 :(得分:1)

It should be if holder == parkingLot[x]. As when you use in, it means, you are searching for something in a sequence, ie a list or a tuple or a dictionary.

For integers, == should be used.

答案 3 :(得分:1)

TerryA is completely correct about the error.

In Python, you can make this sort of error much less likely by using built in functions to work with lists and other iterables instead of directly manipulating lists.

In this case, you could make use of a list comprehension to build the data set for you. For example:

def showSpots(holder):
  for space in [ index for index,value in enumerate(parkingLot) if value == holder ]:
    print (space)

The enumerate function will transform your input into index/value pairs which you can use to construct a list containing only the data you care about. Because you never directly need to manipulate your input list, ther e is no need to worry about the list size and no chance of mixing iterable and non-iterable values.