在Python中,将输入中的值附加到子列表中

2024-10-02 02:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将输入中的值附加到列表中的子列表中。 每个学生的人数和姓名都应该在一个子列表中。 例如:

[[123,John],[124,Andrew]]

外部列表是学生人数,子列表是学生的信息。。在

下面是我的代码:

^{pr2}$

如果我打开第一个循环,snumber = 123name = john,和snumber = 124name = andrew在第二次时它将显示给我:[[123,john,124,andrew]],而不是{}。在


Tags: 代码name信息列表john学生姓名人数
2条回答

您的代码可以大大简化:

  1. 您不需要预先分配列表和子列表。只要有一个列表,并在接收输入时附加子列表。在
  2. 您不需要将用户输入从input转换为字符串,因为它们已经是字符串了。在

修改后的代码如下:

listStudents = []

while True:
    choice = int(input('1- Register Student 0- Exit'))
    if choice == 1:
        snumber = input('Student number: ')
        name = input('Name : ')
        listStudents.append([snumber, name])
    if choice == 0:
        print('END')
        break

print(listStudents)

您的代码可以更python,也可以使用一些基本的错误处理。在while循环中创建内部列表,并简单地附加到外部学生列表中。这应该行得通。在

students = []
while True:
    try:
        choice = int(input("1- Register Student 0- Exit"))
    except ValueError:
        print("Invalid Option Entered")
        continue

    if choice not in (1, 9):
        print("Invalid Option Entered")
        continue

    if choice == 1:
        snumber = str(input("Student number: "))
        name = str(input("Name : "))
        students.append([snumber, name])
    elif choice == 0:
        print("END")
        break

print(students)

相关问题 更多 >

    热门问题