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

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

如有任何帮助,我们将不胜感激!

最佳答案

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

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

尝试将初始化移动到循环之上,使其只执行一次。

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

关于python - 使用循环将对象添加到列表(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2663391/

相关文章:

python - 将外部系统终端连接到 Spyder

Python:导入文件并转换为列表

java - 程序涉及使用距离函数

xcode - Swift 1.2 - 列表类型未声明

python - 如何在Python中将十进制数转换为字节列表

python - txpostgres 存储过程返回游标

string - 如何将 selenium webelements 转换为 python 中的字符串列表

delphi - 怎样才能实现免费的Interface类呢?

python - 如何在 travis-ci 中设置环境变量并从 python 脚本访问它们?

python - 包含元组的 If 语句以及从列表中删除元组