【问题标题】:Using a Loop to add objects to a list(python)使用循环将对象添加到列表(python)
【发布时间】:2011-02-09 10:35:02
【问题描述】:

我正在尝试使用 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")

任何帮助将不胜感激!

【问题讨论】:

  • 所有命名为guess的变量都应该命名为choice my wrong
  • 您可以编辑您的问题;)
  • 哈哈,我试过了,但我得到了 LOLcat 的该死的错误消息页面

标签: python list object loops while-loop


【解决方案1】:

在循环中自动增加索引:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 所以在循环外我应该有 a=[] 然后在循环内我应该有 a.append(s)?
    • @Will:这可能是一个好的开始,尽管您的代码还有其他一些问题。如果您输入 0 或 1 以外的数字,您将再次将同一学生添加到列表中。这真的是你想要的吗?
    • 哈哈,嗯,不……我希望每次选择 1 时都能循环并添加一个不同的学生……所以我会经历一次,添加一个学生,选择1 再次添加一个不同的学生......等等......等等,所以每次我经历我都可以添加一个不同的学生
    • 但在循环结束时,我会让用户输入学生班级的新信息,这样就不会取代旧信息吗?
    • @Will:我会将附加到列表的代码移动到 if choice == 1: 块内。它不应该在其他情况下运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2015-08-29
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2015-07-31
    • 2018-05-19
    相关资源
    最近更新 更多