Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Tuples Python

Tags:

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!

like image 930
Sean Avatar asked Jun 16 '11 12:06

Sean


People also ask

Can you sort tuples in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

Is it possible to sort a tuple?

To sort elements of a tuple, we can use the sorted function, providing the tuple as the first argument. This function returns a sorted list from the given iterable, and we can easily convert this list into a tuple using the built-in function tuple. We can use the two optional parameters (key and reverse) as well.

How do you sort a set of tuples?

In python, to sort list of tuples by the first element in descending order, we have to use the sort() method with the parameter ” (reverse=True) “ which will sort the elements in descending order.

How do you sort a tuple in Python without sorting?

You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.


2 Answers

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 ..

like image 97
mouad Avatar answered Oct 14 '22 11:10

mouad


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

like image 27
Ignacio Vazquez-Abrams Avatar answered Oct 14 '22 12:10

Ignacio Vazquez-Abrams