I am currently trying to sort the following list:
list_ = [(1, '0101'), (1, '1010'), (1, '101'), (2, '01'), (2, '010'), (2, '10')]
These are the steps I want to take in order to sort it:
- Sort the list by the value of the first element of the tuples
- Next, sort the list by the length of the second element of the tuples (not the value, the length!) AFTER step 1 finishes.
- Next, sort the list by the value of the second element of the tuples AFTER step 1 and step 2 finishes.
My attempt:
sorted_by_length = sorted(list_, key=len x:x[1])
However, I received a syntax error concerning the x
after key= len
.
What is the right variable I should be using in this case?
The correct, sorted list should be:
sorted_by_length = [(1, '101'), (1, '0101'), (1, '1010'), (2, '01'), (2, '10'), (2, '010')]
Thank you for help.
The key function can return a tuple.
sorted_by_length = sorted(list_,key=lambda x: (x[0], len(x[1]), float(x[1])))
This works because tuples are sorted lexicographically: (the first element of the tuple is used for sorting first, then the second element is used for breaking ties, and then the third element is used for breaking any remaining ties.)
See the excellent HOWTO Sort for an explanation of this and other issues related to sorting.
In [1]: list_ = [(1, '0101'), (1, '1010'), (1, '101'), (2, '01'), (2, '010'), (2, '10')]In [2]: sorted_by_length = sorted(list_,key=lambda x: (x[0], len(x[1]), float(x[1])))...:
In [3]: sorted_by_length
Out[3]: [(1, '101'), (1, '0101'), (1, '1010'), (2, '01'), (2, '10'), (2, '010')]
If the second element of each tuple is the string representation of an int
in binary, then use int(x, 2)
instead of float(x)
in the sort key. If they are intended to be the decimal representation of an integer, then use int(x)
.