<p>如果允许我对你的代码进行摇滚,我会按照以下思路做些事情:</p>
<pre><code>import operator
score = 10 # for instance
print(f'Score: {score}')
name = input('Enter your name: ')
scoresData = f'{score}-{name}'
print(scoresData)
with open('scores.txt', 'a') as database: # yea i know
database.write(scoresData + '\n')
# -
scoresList = {}
with open('scores.txt', 'r') as database:
for row in database:
score, player = row.split('-', 1)
scoresList[player.strip('\n')] = int(score) # Remove \n from the player name and convert the score to a integer (so you can work on it as an actual number)
for row in sorted(scoresList.items(), key=operator.itemgetter(1)): # Sort by the value (item 1) of the dictionary
print('Player: {} got a score of {}'.format(*row))
</code></pre>
<p>排序由<a href="https://stackoverflow.com/a/613218/929999">[A]How do I sort a dictionary by value?</a><br/>
如果你想玩得很花哨,你可以:</p>
^{pr2}$
<p>或再次加载值:</p>
<pre><code>with open('scores.db', 'rb') as database:
scoreList = pickle.load(database)
</code></pre>
<p>这样就不需要解析文本文件了。您不必担心执行<code>player.strip('\n')</code>,因为不会有任何新行等需要处理。通过pickle进行内存转储的缺点是,我是一个“内存转储”,这意味着在适当的地方编辑值是不可能的/直接的。在</p>
<p>另一个好的解决方案是使用<a href="https://stackoverflow.com/questions/14209868/how-to-work-with-sqlite3-and-python">sqlite3</a>,但是,如果您不习惯于使用数据库,它会变得相当复杂,相当快。如果你准备好了,那绝对是你长期以来最好的选择。在</p>