对个位数和两位数的混合数字进行排序



我正在制作一个游戏,你可以猜出它的艺术家的一首歌,并提供一些字母。我想创建一个高分列表,但是,我发现这很困难,因为当我有 9 和 12 等分数时,python 将 9 排序为高于 12,因为 1<9。如果可以的话,我希望得到一些帮助。

print('Score: ' + str(score))
name = input('Enter your name: ')
scoreAppender.append(str(score))
scoreAppender.append(name)
scoresData = '-'.join(scoreAppender)
print(scoresData)
scoresfile = open('scores.txt', 'a')
scoresfile.write(scoresData + 'n')
scoresfile.close()
scoresfile = open('scores.txt', 'r')
scoresList = []
for score in scoresfile:
scoresList.append(score)
scoresList.sort(key = lambda x: x.split('-')[0])
for score in scoresList:
print(score)
scoresfile.close()

只需在排序键lambda中转换为int

scoresList.sort(key = lambda x: int(x.split('-')[0]))

如果我被允许在你的代码上摇滚,我会做一些类似的事情:

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

排序由 [A] 提供,如何按值对字典进行排序?
如果你想变得非常花哨,你可以做到:

import pickle
...
with open('scores.db', 'wb') as database:
pickle.dump(scoreList, database)

或者再次加载值:

with open('scores.db', 'rb') as database:
scoreList = pickle.load(database)

这消除了解析文本文件的需要。您不必担心执行player.strip('n'),因为不会有任何换行符等需要处理。通过泡菜进行内存转储的缺点是 i 是一个"内存转储",这意味着就地编辑值并不完全可行/直接。

然而,另一个好的解决方案是使用 sqlite3 - 如果你不习惯使用数据库,它会变得相当复杂。如果您愿意,那绝对是您长期的最佳路线。

最新更新