如何在 python 的嵌套列表中附加变量

How to append variables in nested list in python

if __name__ == '__main__':
    for _ in range(int(input())):
        name = input()
        score = float(input())
        a=[]
        a.append([name][score])
    print(a)

这是我插入值时发生的错误

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Nested Lists.py", line 6, in <module>
    a.append([name][score])
TypeError: list indices must be integers or slices, not float

使用字典而不是列表(列表可以,但对于你正在做的事情,hashmap 更适合):

if __name__ == '__main__':
    scores = dict()
    for _ in range(int(input())):
        name = input()
        score = float(input())
        scores[name] = score
    print(scores)

创建包含 namescore 的列表的语法是 [name, score][name][score] 表示创建一个仅包含 [name] 的列表,然后使用 score 作为该列表的索引;这不起作用,因为 scorefloat,列表索引必须是 int.

您还只需初始化一次外部列表。将 a=[] 放入循环内会覆盖您在先前迭代中附加的项目。

a=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    a.append([name, score])
print(a)

正如其他人所说,字典可能是这种情况的最佳解决方案。

但是,如果要将具有多个值的元素添加到列表中,则必须创建子列表 a.append([name, score]) 或元组 a.append((name, score))

请记住,元组无法修改,因此如果您想更新用户的分数,您必须从列表中删除相应的元组并添加一个新元组。

如果您只想向平面列表添加新值,只需选择 a = a + [name, score]。这会将 namescore 作为完全独立的元素添加到列表的末尾。