从空格分隔的单行用户输入中制作学生词典,其中姓名将是关键,考试编号列表将是值



假设我使用一个字符串以一行空格分隔输入为:john 100 89 90
现在从这个字符串中生成一个字典为:d={'john':[100,89,90]}。在这里,数字将作为整数收集在一个列表中。基本上,从输入字符串行,我想制作一个学生信息字典,其中名称将是关键,数字将是作为整数收集在列表中的考试数字。

st=input()
value=st[1:]
c=list(map(int, value.split()))
print(c)
key=st[0]
d={}
d[key]=c
print(d)

我在写这个,但写错了key=st[0]。。但这只会将第一个字符j作为名称,其余作为值,所以我最终得到了错误:基数为10的int((的无效文字:"ohn"那么,我该如何纠正它并得到我上面提到的确切结果呢??我还想知道除了字符串之外的其他方法,比如john 100 89 90。

你的方法在某种程度上是正确的,我想做的唯一补充是,为学生输入信息设置一个预设的分隔符字符串

student_dict = {}
loop_flag = True
loop_input = "Y"
delimit = "," #### You preset delimiter
while loop_flag:
key = input("Input Student Name : ")
if key in student_dict:
print("Student already in Dictionary, continuing...."
continue
else:
info_str = input("Input Student Information: ")
info_list = info_str.split(delimit)
student_dict[key] = info_list

loop_input = input("Do you wish to add another student (Y/N)"

if loop_input == "N":
loop_flag = False

您甚至可以使用空格分隔符,但建议使用更直观的分隔符

最新更新