【问题标题】:Printing the names of highest scorers from text file从文本文件中打印最高得分者的名字
【发布时间】:2021-07-22 06:47:58
【问题描述】:

如果我打开一个包含人名及其分数的文本文件,如果有 2 个人都得分最高,我如何打印这两个名字。现在它只打印其中一个名称,我希望它打印两个,其他一切正常。提前致谢!!

这是我现在的代码:

maxName = ''
maxScore = 0
for line in file:
    i = line.strip().split()
    x = [int(y) for y in i[1:]]
    #print(z[0]," made ","$",sum(x))
    if sum(x) >= maxScore:
        maxName  = z[0]
        maxScore = sum(x)
print(f'The max total score is {maxScore}')       
print(f'those who scored the highest: {maxName}')

【问题讨论】:

    标签: python python-3.x file for-loop tuples


    【解决方案1】:

    它只打印一个,因为您只跟踪一个。要打印多个,请将它们全部记录在一个列表中。

    maxNames = []  # Keep names in this list
    maxScore = 0
    for line in file:
        i = line.strip().split()
        x = [int(y) for y in i[1:]]
        
        #### Only calculate the sum once
        totalScore = sum(x)
    
        if totalScore > maxScore: # If greater, create a new list containing only this name
            maxNames  = [i[0]]
            maxScore = totalScore
        elif totalScore == maxScore: # If equal, append this name to the list
            maxNames.append(i[0])
    
    
    print(f'The max total score is {maxScore}')       
    print(f'those who scored the highest: {maxNames}')
    

    要打印列表中的项目不附带括号和分隔符,您可以str.join() the elements in the list

    printNames = ",".join(maxNames)
    print(f'those who scored the highest: {printNames}')
    

    【讨论】:

      【解决方案2】:

      你可以先找到最高分,然后是所有有这个分数的人:

      lines = [i.strip('\n').split() for i in file]
      max_score = max([sum(b) for _, *b in lines])
      has_max = [a for a, *b in lines if sum(b) == max_score]
      

      【讨论】:

        【解决方案3】:

        将它们存储在一个列表中。我替你把i改成了z

        maxName = []
        maxScore = 0
        for line in file:
            z = line.strip().split()
            x = [int(y) for y in z[1:]]
            #print(z[0]," made ","$",sum(x))
            if sum(x) > maxScore:
                maxName  = [z[0]]
                maxScore = sum(x)
            elif sum(x) == maxScore:
                maxName.append( z[0] )
        print(f'The max total score is {maxScore}')       
        print(f'those who scored the highest: {maxName}')
        

        【讨论】:

          猜你喜欢
          • 2021-05-08
          • 2017-02-08
          • 1970-01-01
          • 1970-01-01
          • 2022-11-13
          • 1970-01-01
          • 2023-03-06
          • 2021-08-17
          • 2012-11-05
          相关资源
          最近更新 更多