【问题标题】:Sum key-values pairs in a text file对文本文件中的键值对求和
【发布时间】:2020-10-23 11:38:16
【问题描述】:

我的 for 循环无法正常工作。
我想对相同的键进行分组并对它们的值求和。 例如,将所有yes 值相加并显示在一行中。 game.txt 中的信息如下所示:

yes 5
maybe 9
yes 2
maybe 10
maybe 7
no 25
yes 1

印刷品是这样的;

{'no': '25', 'yes': '1', 'maybe': '10'}

我的代码是这样的;

test_scores = {}

filename = input("Enter the name of the score file: ")
file = open(filename, mode="r")

print("Contestant score: ")

for file_line in sorted(file):
    key, value = file_line.split()
    if key not in test_scores:
        test_scores.update({key: value})

print(test_scores)

那么问题似乎是什么以及如何解决呢?

【问题讨论】:

  • 您希望打印出来的效果如何?您使用的是字典,因此每个键只能出现一次。
  • 你想对这些值求和吗?
  • 对不起,应该更具体。我需要总结每一个是,不是,也许在一起,所以我需要一个打印,可能有 26 no 25 yes 8,按字母顺序,在单独的行中。我对编码很陌生。

标签: python file dictionary for-loop


【解决方案1】:

您可以执行以下操作:

for file_line in file:
    key, value = file_line.split()
    test_scores[key] = test_scores.get(key, 0) + int(value)

for k, v in sorted(test_scores.items()):
    print(k, v)

dict.update(...) 只是覆盖这些值。您可以使用collections.Counter,它可以更自然地处理计数:

from collection import Counter

test_scores = Counter()
# ...
for file_line in file:
    key, value = file_line.split()
    test_scores[key] += int(value)
    # update would work, too, here
    # test_scores.update({key: int(value)})
# ...

【讨论】:

  • 非常感谢!它运作良好。我只需要输入 + int(value) 才能对这些值求和。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多