如何在Python中分离AnaMeansCoreList?

2024-05-14 21:57:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试过这个:

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

Tags: themattopen分数listfilepeterrow
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)

我建议做一本字典:

# 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、JSONO或仅以这种方式保存

您可以使用^{}进行此操作

代码:

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

这适用于Python3

输出:

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

相关问题 更多 >

    热门问题