我有一个文本文件,以下列格式存储数据:
Mike 6 4 3
Terry 4 3 4
Paul 10 7 8
jvecsei昨天用一些代码帮助我检索数据并确定每个人的最高分。我稍微修改了它,现在它选择得分并打印每个人的平均值。
with open ("classa.txt") as f:
content = f.read().splitlines()
for line in content:
splitline = line.split(" ")
name = splitline[0]
score = splitline[1:]
total = int(splitline[-1]) + int(splitline[-2]) + int(splitline[-3])
average = int(total/3)
print("{} : {}".format (name, average))
它输出像这样,很棒:
Mike : 4
Terry : 3
Paul : 8
问题:我真的很喜欢将这三个人排成最高分的顺序,这样他们就会出现最高得分者和最低得分,就像这样:
Paul : 8
Mike : 4
Terry : 3
我过去曾用过这个来从文本文件中检索并按字母顺序排序,但由于平均值是一个新变量并且没有与原始数字一起存储在文本文件中,我不知道如何参考/实施它。
with open('classc.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
非常感谢你的帮助。我正逐渐对这些东西越来越熟悉,但我还有很长的路要走。
答案 0 :(得分:0)
将您的Name : Average
输出存储到字典中,然后使用operator.itemgetter
对字典进行排序
d = {}
with open ("file.txt") as f:
content = f.read().splitlines()
for line in content:
splitline = line.split(" ")
name = splitline[0]
score = splitline[1:]
total = int(splitline[-1]) + int(splitline[-2]) + int(splitline[-3])
average = int(total/3)
print("{} : {}".format (name, average))
d[name] = average
sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse= True)
for i in sorted_d:
print '{} : {}'.format(*i)
输出:
Paul : 8
Mike : 4
Terry : 3
答案 1 :(得分:0)
我用这个问题来说明Python 3.5中一些不错的新功能。您可以使用new statistics module和generalized unpacking以非常pythonic的方式解决此问题:
>>> from statistics import mean # Cool new module!
>>> lines =(l.split() for l in open ("classa.txt")) # Generator consuming the file
# Now split the list by unpacking into name, *scores
>>> persons = ((mean(int(x) for x in scores), name) for name, *scores in lines)
>>> for score in sorted(persons, reverse=True): # Some boring I/O
print("{} : {}".format (score[1], int(score[0])))
>>>
Paul : 8
Mike : 4
Terry : 3 # Terry really needs to step up his game
以下是更传统的python代码:
>>> def mean(x):
return sum(x)/len(x)
>>> lines =(l.split() for l in open ("classa.txt"))
>>> persons = ((mean([int(x) for x in l[1:]]), l[0]) for l in lines)
>>> for score in sorted(persons, reverse=True):
print("{} : {}".format (score[1], int(score[0])))
>>>
Paul : 8
Mike : 4
Terry : 3
答案 2 :(得分:0)
您可以编写一个函数,计算分数的平均值,然后基于该分数进行排序。请注意,您的函数将进行计算,平均值实际上不需要“存储”在原始文件/数据的任何位置-
def mysort(line):
score1, score2, score3 = map(int, line.split()[1:])
average = (score1 + score2 + score3) / 3
return -1*average, line.split()[0]
with open("score-sheet.txt", "r") as f:
text = f.readlines()
for line in sorted(text, key=mysort):
print line