使用循环将对象添加到列表(python) [英] Using a Loop to add objects to a list(python)

查看:40
本文介绍了使用循环将对象添加到列表(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use a while loop to add objects to a list.

这基本上是我想要做的:

Here's basically what I want to do:

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))))

我可以将对象添加到列表中,但我无法在循环中将多个对象添加到列表中.

I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.

这是我目前的代码:

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

任何帮助将不胜感激!

推荐答案

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

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

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

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

Try moving the initialization above the loop so that it is executed only once.

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

这篇关于使用循环将对象添加到列表(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆