Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对文本文件中的键值对求和_Python_File_Dictionary_For Loop - Fatal编程技术网

Python 对文本文件中的键值对求和

Python 对文本文件中的键值对求和,python,file,dictionary,for-loop,Python,File,Dictionary,For Loop,我的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:

我的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)
我的代码如下所示

{'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)

那么问题出在哪里以及如何解决呢?

您可以执行以下操作:

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)})
# ...

你想让指纹看起来像什么?您正在使用字典,因此每个键只能出现一次。是否要对值求和?对不起,应该更具体一些。我需要把每一个是,不是,也许加在一起,所以我需要一张打印出来,可能有26个不是25个是8,按字母顺序,在单独的行中。我对编码很陌生。非常感谢!它工作得很好。我只需要输入+int(value)就可以对这些值求和了。