如何在Python中分离a-name和score-list



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

我试过这个:

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

我建议制作一本字典:

# 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(显示/保存此词典,也可以仅保持这样。

您可以为此使用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

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

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)

您可以使用以下内容

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

演示

我只使用标准字典(而不是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

相关内容

最新更新