If i have a list of numbers [4,2,5,1,3]
I want to sort it first by some function f
and then for numbers with the same value of f
i want it to be sorted by the magnitude of the number.
This code does not seem to be working.
list5 = sorted(list5) list5 = sorted(list5, key = lambda vertex: degree(vertex))
Secondary sorting first: list5 is sorted based on magnitude. Primary sorting next: list5 is sorted based on some function of the numbers.
Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.
Secondary sorting means sorting to be done on two or more field values of the same or different data types. Additionally we might also have deal with grouping and partitioning. The best and most efficient way to do secondary sorting in Hadoop is by writing our own key class.
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.
Sort it by a (firstkey, secondkey) tuple:
sorted(list5, key=lambda vertex: (degree(vertex), vertex))
From the Python 3 docs on sorting
from operator import itemgetter, attrgetter student_objects = [ Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'B', 10), ] student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] #The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age: sorted(student_tuples, key=itemgetter(1,2)) sorted(student_objects, key=attrgetter('grade', 'age'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With