【问题标题】:How to separate a-name-and-score-list in Python?如何在 Python 中分隔名称和分数列表?
【发布时间】:2020-02-26 21:11:25
【问题描述】:

所以我有这个任务,我必须从文本文件中计算玩家的分数,然后打印分数。如何拆分名称和分数并计算特定名称的分数?并且名称必须按字母顺序排列。

我试过这个:

file = input("Enter the name of the score file: ")
    print("Contestant score:")
    open_file = open(file, "r")
    list = open_file.readlines()
    open_file.close()
    for row in sorted(list):
        row = row.rstrip()
        contestant = row.split(" ")
    if contestant[0] == contestant[0]:
        total = int(contestant[1]) + int(contestant[1])
        print(contestant[0], total)
    print(row)

文本文件示例:

sophia 2

sophia 3

peter 7

matt 10

james 3

peter 5

sophia 5

matt 9

程序应该是这样的:

james 3

matt 19

peter 12

sophia 10

而我目前的输出是:

sophia 10

sophia 5

【问题讨论】:

  • 您当前的代码提供了什么结果?请列出您当前的输出以及您的预期输出
  • 你的缩进关闭了,或者我不明白你试图用那个 if 实现什么。说到这里,您想用if contestant[0] == contestant[0]: 实现什么Edit您的帖子并解释您的算法。 (并且不要使用 list 作为变量名。它在 Python 中有点像 taken。)

标签: python python-3.x list file


【解决方案1】:

我建议制作一本字典:

# Open Text File
file = input("Enter the name of the score file: ")
print("Contestant score:")
open_file = open(file, "r")
lines = open_file.readlines()

# Convert into one single line for ease
mystr = '\t'.join([line.strip() for line in lines])

# Split it and make dictionary
out = mystr.split()
entries = dict([(x, y) for x, y in zip(out[::2], out[1::2])])

# Unsorted Display
print(entries)

# Sorted Display
print(sorted(entries.items(), key=lambda s: s[0]))

输出:

[('james', '3'), ('matt', '9'), ('peter', '5'), ('sophia', '5')]

您可以以任何您喜欢的形式显示/保存此字典,例如 CSV、JSON 或仅保留它。

【讨论】:

    【解决方案2】:

    您可以为此使用collections.defaultdict

    代码:

    from collections import defaultdict
    
    file = input("Enter the name of the score file: ")
    results = defaultdict(int)
    with open(file, "r") as file:
        # Gather results from each line.
        for line in file:
            name, points = line.split()
            results[name] += int(points)
    
    # Print the results dict.
    print("Contestant score:")
    for name in sorted(results.keys()):
        print(name, results[name])
    

    这适用于 Python 3。

    输出:

    Enter the name of the score file: input.txt
    Contestant score:
    james 3
    matt 19
    peter 12
    sophia 10
    

    【讨论】:

      【解决方案3】:

      您可以使用字典来存储每个玩家的总分。

      from collections import defaultdict
      scores=defaultdict(int)
      with open('score.txt','r') as f:
          for line in f:
              if line.strip():
                  key,val=line.split()
                  scores[key]+=int(val)
      
      print(*sorted(scores.items()),sep='\n')
      

      输出:

      ('james', 3)
      ('matt', 19)
      ('peter', 12)
      ('sophia', 10)
      

      【讨论】:

        【解决方案4】:

        你可以使用类似的东西:

        import os
        from collections import defaultdict
        file = input("Enter the name of the score file: ").strip()
        results = defaultdict(int)
        if(os.path.isfile(file)):
            with open(file) as f:
                for row in sorted([x.strip() for x in list(f) if x]):
                    line = row.split()
                    if len(line) == 2:
                        results[line[0]] += int(line[1])
        
                print("Contestants scores:")
                for k, v in results.items():
                    print(k, v)
        else:
            print("File not found", file)
        

        Contestants scores:
        james 3
        matt 19
        peter 12
        sophia 10
        

        demo

        【讨论】:

          【解决方案5】:

          我只使用标准字典(不是collections.defaultdict)制定了一个解决方案,所以我想我也会发布它。

          Python 3

          代码:

          file = input("Enter the name of the score file: ")
          print("Contestant score:")
          
          gamer_dict = {}
          with open(file, 'r') as infile:
              for row in infile:
                  splits = row.split(" ")
                  name = splits[0].strip()
                  score = int(splits[1].strip())
                  if name not in gamer_dict:
                      gamer_dict[name] = score
                  else:
                      gamer_dict[name] += score
          
          for k,v in sorted(gamer_dict.items()):
              print(k,v)
          

          输出:

          Enter the name of the score file: gamers.txt
          Contestant score:
          james 3
          matt 19
          peter 12
          sophia 10
          

          【讨论】:

            猜你喜欢
            • 2020-10-18
            • 2018-02-22
            • 2022-11-10
            • 1970-01-01
            • 2023-01-07
            • 1970-01-01
            • 2022-01-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多