繁体   English   中英

如何在 python 的嵌套列表中使用 append 个变量

[英]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

创建包含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)

使用字典而不是列表(列表会起作用,但对于您正在做的事情,hashmap 更适合):

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM