使用用户输入更新嵌套列表

update nested list with user input

我正在处理的程序中的一个函数获取测验分数列表,并要求用户输入回合名称和分数。如果回合已经存在,它将新分数附加到现有列表,否则它将回合及其分数添加到列表的顶层:

lines = [['geography', '8', '4', '7'],
         ['tv and cinema', '4', '4', '8', '7', '7'],
         ['all creatures great and small', '7', '8'],
         ['odd one out', '4', '7'],
         ['music', '3', '5', '8', '8', '7'],
         ['how many', '4']]



roundName = input("Enter the name of the round to add: ")
score = input("Enter the score for that round: ")

for line in lines:
    if roundName in line:
        line.append(score)
lines.append([roundName, score])


#for line in lines:
#    if line[0] == roundName.lower().strip():
#        existingRound = lines.index(line)
#        lines[existingRound].append(score)
#    else:
#        newRound = [roundName, score]
#        lines.append(newRound)

评论部分代表我最初的几次尝试。输入 how many3 应导致

lines = [['geography', '8', '4', '7'],
             ['tv and cinema', '4', '4', '8', '7', '7'],
             ['all creatures great and small', '7', '8'],
             ['odd one out', '4', '7'],
             ['music', '3', '5', '8', '8', '7'],
             ['how many', '4', '3']]
#actually results, in 
[['geography', '8', '4', '7'],
             ['tv and cinema', '4', '4', '8', '7', '7'],
             ['all creatures great and small', '7', '8'],
             ['odd one out', '4', '7'],
             ['music', '3', '5', '8', '8', '7'],
             ['how many', '4', '3'],
             ['how many', '3']]

我无法正确理解循环中的逻辑。我哪里错了?

for line in lines:
    if roundName in line:
        line.append(score)
lines.append([roundName, score])

在这里,您正在将新回合添加到行中,无论它是否已经存在于行中。只需使用布尔值来指示是否需要添加到行,然后将新一轮附加到行更改为条件:

add = True
for line in lines:
    if roundName in line:
        line.append(score)
        add = False
if add: lines.append([roundName, score])

如果顺序无关紧要,尽管使用字典会容易得多:

lines = {'geography':['8', '4', '7'], 'tv and cinema': [...] ...}

roundName = input("Enter the name of the round to add: ")
score = input("Enter the score for that round: ")

if roundName in lines: lines[roundName].append(score)
else: lines[roundName] = [score]