代码之家  ›  专栏  ›  技术社区  ›  Jim421616

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

  •  0
  • Jim421616  · 技术社区  · 7 年前

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

    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 many ,请 3 会导致

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

    我不能把逻辑弄清楚。我哪里做错了?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Primusa    7 年前
    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]