Python 仅按第一位数字排序的2D列表
此二维列表包含名称和分数。我需要它从第二列按降序值排序Python 仅按第一位数字排序的2D列表,python,python-3.x,list,sorting,Python,Python 3.x,List,Sorting,此二维列表包含名称和分数。我需要它从第二列按降序值排序 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
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']
如图所示,它仅按第一个数字对列进行排序。如何解决此问题?您需要在排序键中将字符串转换为整数:
highScores.sort(key=lambda x: int(x[1]), reverse=True)
否则,正如您所发现的,您的排序将一次处理一个字符,正如您对字符串所期望的那样。这是因为您对字符串类型的整数进行排序,而实际上并不是按int类型进行排序。将第二项显式更改为
int
,然后进行排序