gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:39:32 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com