Sorting lists in python

后端 未结 3 1144
无人共我
无人共我 2020-12-21 18:59

Okay, so I have a bit of a problem, Im new to python sorry.

I am trying to sort a list by score, which is a number, but if there is a draw I need to sort them by the

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 19:22

    You'd have to iterate over each line and use the sort method on them

    #open the file and read through the lines.
    lines = open('yourfile.txt').readlines()
    
    #iterate over each line, and split along the spaces 
    pairs =[]
    for line in lines:
       split_string = line.split('')
       num = int(split_string[0])
       pairs.append((num, split_string[1:])
    
    #sort through the pairs (from mgilsons answer)
    pairs.sort(key=lambda x: (x[0],len(x[1]))
    

    edit: actually misread the question.

提交回复
热议问题