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

时间:2018-10-16 11:04:15

标签: python sorting file-handling

我正在做一个游戏,您在其中猜测艺术家的歌曲并提供一些字母。我想创建一个高分列表,但是,当我获得9和12之类的分数时,我发现这很困难,因为1 <9,python会将9排序为12以上。我想在这方面有所帮助。

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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]How do I sort a dictionary by value?进行的
如果您想花大价钱,可以这样做:

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'),因为将不需要处理任何换行符。通过pickle进行内存转储的缺点是,我是一个“内存转储”,这意味着在原位编辑值是不可能的/直接进行的。

另一个好的解决方案是使用sqlite3,但是-如果您不习惯使用数据库,它将变得相当复杂。如果您愿意,那么这就是您长期以来绝对最佳的路线。