[英]How to sort the top scores from an external text file with the names of the people who achieved those scores still linked? Python
I have managed to write the scores and names of anybody who wins a simple dice game I created to an external text document.我已经设法将赢得我创建的简单骰子游戏的任何人的分数和姓名写入外部文本文档。 How would I sort the top scores from this document and display them on the console alongside the name that achieved that score?我将如何对本文档中的最高分数进行排序,并将它们与获得该分数的名称一起显示在控制台上?
Code used to write score and name to the text document:用于将分数和名称写入文本文档的代码:
winners = open("winners.txt", "a")
winners.write(p1_username) #writes the name
winners.write("\n")
winners.write(str(p1_total)) #writes the score
Tried entering the data into an array of tuples and sorting them according to the numerical value in each tuple when I found this , so tried当我发现这个时,尝试将数据输入一个元组数组并根据每个元组中的数值对其进行排序,所以尝试了
count = len(open("winners.txt").readlines( ))
winners_lst = [(None, None)] * count
f = open("winners.txt", "r")
lines2 = f.readlines()
winners_lst[0][0] = lines2[0]
winners_lst[0][0] = lines2[1]
but that returns但这又回来了
TypeError: 'tuple' object does not support item assignment
Edit: I am not asking why my solution didn't work, I am asking what I could do to make it work or for an alternate soloution.编辑:我不是在问为什么我的解决方案不起作用,我是在问我可以做些什么来使它起作用或替代解决方案。
Tuples are immutable, which means you cannot modify a tuple once it has been created.元组是不可变的,这意味着一旦创建元组就不能修改它。 You have two options to achieve what you want:您有两种选择来实现您想要的:
winners_lst = [[None, None]] * count
使用大小为 2 的列表而不是元组,如下所示: winners_lst = [[None, None]] * count
winners_lst[0] = (lines2[0], lines2[1])
用另一个替换元组,如下所示: winners_lst[0] = (lines2[0], lines2[1])
First, the write operation should be cleaner:首先,写操作应该更干净:
with open('winners.txt', 'w') as f:
for p1_username, p1_score in [('foo', 1), ('bar', 2), ('foobar', 0)]:
print(f'{p1_username}\n{p1_score}', file=f)
Content of winners.txt
: winners.txt
的内容:
foo
1
bar
2
foobar
0
Then, you can read this back into a list of tuples:然后,您可以将其读回到元组列表中:
with open('winners.txt') as f:
lines = f.read().splitlines()
winners_lst = [(a, b) for a, b in zip(lines[::2], lines[1::2])]
Content of winners_lst
: winners_lst
的内容:
[('foo', '1'), ('bar', '2'), ('foobar', '0')]
After ingest, you may convert the scores into int
:摄取后,您可以将分数转换为int
:
winners_lst = [(a, int(b)) for a, b in winners_lst]
And sort by score descending (if such is your goal):并按分数降序排序(如果这是您的目标):
sorted(winners_lst, key=lambda ab: ab[1], reverse=True)
# out:
[('bar', 2), ('foo', 1), ('foobar', 0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.