对一位数和两位数的混合排序

2024-06-16 12:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个游戏,你猜一首歌的艺术家和一些信提供。我想创建一个高分列表,但是我发现这很困难,因为当我有诸如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()

Tags: nameintxtforcloseopenscoreprint
2条回答

如果允许我对你的代码进行摇滚,我会按照以下思路做些事情:

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]How do I sort a dictionary by value?
如果你想玩得很花哨,你可以:

^{pr2}$

或再次加载值:

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

这样就不需要解析文本文件了。您不必担心执行player.strip('\n'),因为不会有任何新行等需要处理。通过pickle进行内存转储的缺点是,我是一个“内存转储”,这意味着在适当的地方编辑值是不可能的/直接的。在

另一个好的解决方案是使用sqlite3,但是,如果您不习惯于使用数据库,它会变得相当复杂,相当快。如果你准备好了,那绝对是你长期以来最好的选择。在

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

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

相关问题 更多 >