Python 获取列表外分配索引超出范围

Python 获取列表外分配索引超出范围,python,indexing,Python,Indexing,不知道为什么会超出范围。我将范围设置为0到5。 这是我的密码 class Car(object): def __init__ (self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage self.price = price i

不知道为什么会超出范围。我将范围设置为0到5。 这是我的密码

class Car(object):
    def __init__ (self, price, speed, fuel, mileage):
        self.price = price
        self.speed = speed
        self.fuel = fuel
        self.mileage = mileage
        self.price = price
        if price > 1000:
            self.tax = 15
        else:
            self.tax = 12
    def displayAll(self):
        print "Price: " + str(self.price)
        print "Speed: "  + str(self.speed) 
        print "Fuel: " + str(self.fuel)
        print "Mileage: " + str(self.mileage)
        print "Tax: 0." + str(self.mileage) 

auto = [5]
for car in range(0,5):
    price = input("How much does the car cost? ")
    speed = input("Mile per hour? ")
    mileage = input("Mile per gallon? ")
    fuel = raw_input("How much fuel? ")
    print car
    auto[car] = Car(price, speed, fuel, mileage)

Auto是一个由一个条目组成的矩阵,即数字5,即[5]。您希望它是一个包含5个条目的矩阵。

Auto是一个包含一个条目的矩阵,即数字5,即[5]。您希望它是一个包含5个条目的矩阵。

您将auto设置为
auto=[5]
,但它应该是
auto=[None]*5
auto=range(5)


否则,您将创建一个长度为1的列表,并且在调用
auto[car]

时会出现越界错误。您将auto设置为
auto=[5]
,但它应该是
auto=[None]*5
auto=range(5)


否则,您将创建一个长度为1的列表,并且在调用
auto[car]

时将出现越界错误,这是因为您只创建了一个包含一个元素
5
的列表。编写此代码的更好方法可能是

auto = []
for car in range(0,5):
    price = input("How much does the car cost? ")
    speed = input("Mile per hour? ")
    mileage = input("Mile per gallon? ")
    fuel = raw_input("How much fuel? ")
    print car
    auto.append(Car(price, speed, fuel, mileage))

这是因为您正在创建一个列表,其中包含一个元素
5
。编写此代码的更好方法可能是

auto = []
for car in range(0,5):
    price = input("How much does the car cost? ")
    speed = input("Mile per hour? ")
    mileage = input("Mile per gallon? ")
    fuel = raw_input("How much fuel? ")
    print car
    auto.append(Car(price, speed, fuel, mileage))

从空列表开始并使用
append()
。从空列表开始并使用
append()