如何通过用户输入将字符串和整数放入列表中

How to put string and integer in list by user input

你能建议我如何将整数和字符串放入列表的子列表中吗?例如:

示例输入:

Harry
37.21
Berry
37.21
Charli
37.2
Ron
41
Jack
39

示例输出:

[['Harry', 37.21], ['Berry', 37.21], ['Charli', 37.2], ['Ron', 41], ['Jack', 39]]

我试过这个:

students = []
for i in range(int(input("Enter num of students: "))):
    name = input("name of student: ")
    score = float(input("score:  "))
    students.append(name)
    students.append(score)
print(students)

但我得到这个:

['test1', 23.1, 'test2', 53.32]

附加 tuple(或 list)而不是单个值:

students = []
for i in range(int(input("Enter num of students: "))):
    name = input("name of student: ")
    score = float(input("score:  "))
    students.append((name, score))
    # students.append([name, score]) # alternatively
print(students)

我建议使用 tuples 而不是列表。元组类似于列表,但创建后不能修改。我想这在你的例子中更有意义,因为你的 (student, score) 是一个数据结构。还有 tuples are faster 因为它们是不可变的。