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

时间:2016-06-13 20:49:22

标签: 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
        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)

3 个答案:

答案 0 :(得分:2)

这是因为您只是在其中创建一个包含一个元素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)) 的列表。编写此代码的更好方法可能是

{{1}}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您将自动设为auto=[5],但应为auto=[None]*5auto=range(5)

否则你创建一个长度为1的列表,并在调用auto[car]时出现越界错误