how can I sort the list below based on the b component instead of the a component if I use the sorted()
method in Python
list = [(a1,b1),(a2,b2),(a3,b3)]
how can I sort the list below based on the b component instead of the a component if I use the sorted()
method in Python
list = [(a1,b1),(a2,b2),(a3,b3)]
You can use the sort-key to set a specific function to decide the sorting criterion. In this case it might be enough to just pick the second value for each entry, i.e. x[1]
. See here for more information on the sort
and sorting
functions.
sorted_list = sorted(unsorted_list, key=lambda x: x[1])
and, for example, if you notice that you want to sort in descending and not ascending order:
sorted_list = sorted(unsorted_list, key=lambda x: -x[1])