Sort Tuples Python

40,035

Solution 1

Just do:

print sorted(scores, reverse=True)
[(78495, 'Great Player'), (8473, 'Damian'), (4860, 'Andy'), (2850, 'Bob'), (1489, 'Sean'), (276, 'Crap Player'), (0, 'Stephen')]

you can use scores.sort(reverse=True) if you want to sort in place, and by the way the sort function in case of list of tuple by default sort by first item , second item ..

Solution 2

sorted() returns the sorted sequence. If you want to sort a list in place then use list.sort().

Share:
40,035
Sean
Author by

Sean

Updated on July 09, 2022

Comments

  • Sean
    Sean almost 2 years

    I have a list of tuples in my Blender python code

    scores=[(1489,"Sean"), (2850,"Bob"), (276,"Crap Player"), (78495, "Great Player"), (8473, "Damian"), (4860, "Andy"), (0, "Stephen")]
    

    I'm trying to sort them by their score by using this

    sorted(scores, key=lambda score: score[0], reverse=True)
    

    but this is not working. I have no idea why. Any tips?

    I've considered maybe a better implementation is to create a new Score class with fields name and score

    EDIT:

    Thanks guys for the fast reply

    it was giving me no errors with the sorted method but was not sorting. I used the sort() and it works.

    I think python is just a little weird in Blender maybe?

    Thanks!

  • Robert Hensing
    Robert Hensing almost 13 years
    This will also sort players with identical scores alphabetically, which might be desirable.
  • code_dredd
    code_dredd over 6 years
    @RobertHensing Is there a way to get sorted to not sort by the 2nd key (i.e player names)? Docs say that sorted is guaranteed to be stable, so it should be preserving the original order when the 1ary keys being compared are equal, but it doesn't.
  • code_dredd
    code_dredd over 6 years
    In that case, you actually have to use the key function explicitly. For example: sorted(scores, reverse=True, key=lambda s: s[0])
  • uuu777
    uuu777 about 4 years
    I have three parameters to sort 2 strings and numerical value - what should I do, write function that produces concatenated string of some sort and then compare these strings????