使用循环将对象添加到列表(python)

时间:2010-04-18 18:30:34

标签: python list object loops while-loop

我正在尝试使用while循环将对象添加到列表中。

这基本上就是我想做的事情:

class x:
     pass

choice = raw_input(pick what you want to do)

while(choice!=0):
    if(choice==1):
       Enter in info for the class:
       append object to list (A)
    if(choice==2):
       print out length of list(A)
    if(choice==0):
       break
    ((((other options))))

我可以将对象添加到列表中,但我仍然坚持如何在循环中向列表中添加多个对象。

这是我到目前为止的代码:

print "Welcome to the Student Management Program"

class Student:  
    def __init__ (self, name, age, gender, favclass):  
         self.name   = name  
         self.age    = age  
         self.gender = gender  
         self.fac = favclass  

choice = int(raw_input("Make a Choice: " ))

while (choice !=0):
    if (choice==1):  
        print("STUDENT")  
        namer = raw_input("Enter Name: ")  
        ager = raw_input("Enter Age: ")  
        sexer = raw_input("Enter Sex: ")  
        faver = raw_input("Enter Fav: ")      

    elif(choice==2):
        print "TESTING LINE"
    elif(choice==3):
        print(len(a))

    guess=int(raw_input("Make a Choice: "))

    s = Student(namer, ager, sexer, faver)
    a =[];
    a.append(s)

raw_input("Press enter to exit")

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:25)

问题似乎是您在每次迭代中将列表重新初始化为空列表:

while choice != 0:
    ...
    a = []
    a.append(s)

尝试在循环上方移动初始化,使其仅执行一次。

a = []
while choice != 0:
    ...
    a.append(s)

答案 1 :(得分:0)

循环中自动递增索引:

myArr[(len(myArr)+1)]={"key":"val"}