[英]Python: Assigning multiple values to sublist without using .append()?
[英]Append Values from input to a sublist in Python
我試圖將輸入中的值附加到列表中的子列表中。 每個學生編號和姓名應在一個子列表中。 例如:
[[123,John],[124,Andrew]]
外部列表是學生人數,子列表是學生信息。
這是我的代碼:
listStudents = [[] for _ in range(3)]
infoStudent = [[]]
while True:
choice = int(input("1- Register Student 0- Exit"))
cont = 0
if choice == 1:
snumber = str(input("Student number: "))
infoStudent[cont].append(str(snumber))
name = str(input("Name : "))
infoStudent[cont].append(str(name))
cont+=1
listStudents.append(infoStudent)
if choice == 0:
print("END")
break
print(listStudents)
print(infoStudent)
如果我進行第一個循環, snumber = 123
, name = john
, snumber = 124
, name = andrew
第二次,它將顯示: [[123,john,124,andrew]]
而不是[[123,john], [124,andrew]]
。
您的代碼可以大大簡化:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.