I have some data either in a list of lists or a list of tuples, like this:
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list?
For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let
and so define a lambda that returns a tuple that describes priority, for instance
@Stephen 's answer is to the point! Here is an example for better visualization,
Shout out for the Ready Player One fans! =)
key
is a function that will be called to transform the collection's items for comparison.. likecompareTo
method in Java.The parameter passed to key must be something that is callable. Here, the use of
lambda
creates an anonymous function (which is a callable).The syntax of lambda is the word lambda followed by a iterable name then a single block of code.
Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.
We are sorting this list by time of event occurrence - which is the 0th element of a tuple.
Note -
s.sort([cmp[, key[, reverse]]])
sorts the items of s in placeIn order to sort a list of tuples
(<word>, <count>)
, forcount
in descending order andword
in alphabetical order:I use this method:
and it gives me the result:
Sorting a tuple is quite simple: