允许用户在Python中创建多个列表

时间:2016-02-12 22:35:05

标签: python list

我想用户输入信息并打印出总清单。但是,当用户输入另一个列表时,它只打印出第一个列表。如何使程序打印用户总输入。这是我的代码。

listing = []


class Car:
    def __init__(self, ownerName=None, model=None, make=None, price=None):
        self.ownerName = ownerName
        self.model = model
        self.make = make
        self.price = price

    def input(self):
        print "Please update car info \n"
        while True:
            i = 0
            listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
            print "Updated"
            print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
            addOn = raw_input("Continue? (Y/N)")
            if addOn.lower() == "y":
                i += 1
                continue
            else:
                break

    # search a car and print its information. Exit when user input is 'exit'

def menu():
    x = Car()
    print "PLease choose an option (1-4):\n"
    choice = raw_input("1) input\n" \
          "2) change price and owner\n" \
          "3) search a car and print info\n" \
          "\"exit\" Exit")

    if choice == "1":
        x.input()
    elif choice == "2":
        print "Price"
    elif choice == "3":
        print "Search and Print info"


menu()

3 个答案:

答案 0 :(得分:0)

这是因为您在i循环的每次迭代时重置了while

移动线:

    i = 0
while True:

之前

这应解决当前的问题,但是,您的代码使用了一种不寻常的设计。您不应创建Car对象以创建Car的更多实例,然后将其插入到全局列表中。

至少可以使input()成为静态方法,并让它向调用者返回Car个实例列表。然后,您可以取消全局listing变量。此外,您实际上不需要在i中保留计数器,只需使用-1作为下标即可访问列表中的最后一项:

    @staticmethod
    def input(listing=None):
        if listing is None:
            listing = []

        print "Please update car info \n"
        while True:
            listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
            print "Updated"
            print('{0.ownerName} {0.model} {0.make} {0.price}'.format(listing[-1]))
            addOn = raw_input("Continue? (Y/N)")
            if addOn.lower() != "y":
                break

        return listing

这里使用静态方法很好,因为input()Car个对象有关,所以将该函数打包到类中是有意义的。

现在,您可以在不创建input()实例的情况下致电Car。在menu()功能中,移除x = Car()并将x.input()更改为listing = Car.input()。或者,如果您要附加到现有的“列表”列表,请调用Car.input(listing),这会将新输入附加到listing。然后,您可以打印返回的列表以查看所有用户输入:

def menu():
    print "PLease choose an option (1-4):\n"
    choice = raw_input("1) input\n" \
          "2) change price and owner\n" \
          "3) search a car and print info\n" \
          "\"exit\" Exit")

    if choice == "1":
        listing = Car.input()
        # print out all user entered cars
        for car in listing:
            print('{0.ownerName} {0.model} {0.make} {0.price}'.format(car))
    elif choice == "2":
        print "Price"
    elif choice == "3":
        print "Search and Print info"

答案 1 :(得分:0)

@ mhawke的回答应该可以解决你的问题。但是,我不喜欢从其中一个函数创建类的对象的想法。检查下面的编辑代码。

listing = []


class Car:
    def __init__(self, ownerName=None, model=None, make=None, price=None):
        self.ownerName = ownerName
        self.model = model
        self.make = make
        self.price = price

def input_car():
    print "Please update car info \n"
    i = 0
    while True:
        listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
        print "Updated"
        print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
        addOn = raw_input("Continue? (Y/N)")
        if addOn.lower() == "y":
            i += 1
            continue
        else:
            break

    # search a car and print its information. Exit when user input is 'exit'

def menu():
    #x = Car()
    print "PLease choose an option (1-4):\n"
    choice = raw_input("1) input\n" \
          "2) change price and owner\n" \
          "3) search a car and print info\n" \
          "\"exit\" Exit")

    if choice == "1":
        input_car()
    elif choice == "2":
        print "Price"
    elif choice == "3":
        print "Search and Print info"


menu()

答案 2 :(得分:0)

我清理了一点代码。我现在应该工作。选项3为您提供了目前为止所有汽车的完整列表,因此您有一个可以构建的示例。

listing = []

class Car:
    def __init__(self, ownerName=None, model=None, make=None, price=None):
        self.ownerName = ownerName
        self.model = model
        self.make = make
        self.price = price

    #to have a useful method for our example I overwrite the __str__ method from object
    def __str__(self):
        return ",".join([self.ownerName, self.model, self.make, self.price])


#input does not handle aspects of car, therefore it should be not a method of car
def input():
    print "Please update car info \n"
    while True:
        # there is no need for 'i' so I removed it
        car = Car(raw_input("Owner Name"),
                  raw_input("Model?"),
                  raw_input("Make?"),
                  raw_input("Price?"))
        listing.append(car)
        print "Updated"
        print car #possible since __str__ is overwritten
        addOn = raw_input("Continue? (Y/N)")
        if addOn.lower() == "n":
            break

def menu():
    keep_running = True
    #added a while loop so the user stays in the program until he types 'exit'
    #changed option '3' to have a working example to build on
    while keep_running:
        print "PLease choose an option (1-4):\n"
        choice = raw_input("1) input\n" \
                           "2) change price and owner\n" \
                           "3) list all cars\n" \
                           "\"exit\" Exit")

        if choice == "1":
            input()
        elif choice == "2":
            print "Price"
        elif choice == "3":
            print "\n".join(map(str, listing))
        elif choice == "exit":
            keep_running = False

menu()