此二维列表包含姓名和分数。我需要它从第二列的降序值中排序。
scores = "scores.txt"
highScores = list() # place all your processed lines in here
with open(scores) as fin:
for line in fin:
lineParts = line.split(": ")
if len(lineParts) > 1:
lineParts[-1] = lineParts[-1].replace("\n", "")
highScores.append(lineParts) # sorting uses lists
highScores.sort(key = lambda x: x[1], reverse = True)
print(highScores)
with open('sorted.txt', 'w') as f:
for item in highScores:
f.write(str(item) +"\n")
输入是:
test1: 5
test2: 6
test3: 1
test4: 2
gd: 0
hfh: 5
hr: 3
test: 0
rhyddh: 0
Marty: 5425
testet: 425
place: 84
to: 41
但输出是:
['place', '84']
['test2', '6']
['Marty', '5425']
['test1', '5']
['hfh', '5']
['testet', '425']
['to', '41']
['hr', '3']
['test4', '2']
['test3', '1']
['gd', '0']
['test', '0']
['rhyddh', '0']
如图所示,它仅按第一个数字对列进行排序。我该如何解决这个问题?
答案 0 :(得分:1)
您需要在排序键中将字符串转换为整数:
highScores.sort(key=lambda x: int(x[1]), reverse=True)
否则,正如您所发现的那样,您的排序将一次处理一个字符,正如您对字符串所期望的那样。