Skip to main content
 首页 » 编程设计

python之二维列表仅按第一位排序

2024年12月31日8over140

<分区>

这个二维列表包含姓名和分数。我需要它从第 2 列按降序值排序。

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'] 

如上所示,它仅按第一个数字对列进行排序。我该如何解决这个问题?