【问题标题】:update nested list with user input使用用户输入更新嵌套列表
【发布时间】:2018-06-25 23:35:35
【问题描述】:

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

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']]

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

【问题讨论】:

  • 你绝对应该为此使用字典

标签: python-3.x list nested-lists


【解决方案1】:
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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多