I have a list of lists consisting of two numbers each.
[[2, 3], [7, 8], [3, 5]]
I would like to sort them based on dividing each:
eg 2 / 3 (0.666), 7 / 8 (0.875) 3 / 5 (0.6) to output:
[[3, 5], [2, 3], [7, 8]]
I'm assuming I will be using lambda somehow, but I don't know how to write it correctly. Something like this, but this just sorts by the values:
list_of_lists.sort(key=lambda x: (x[0],x[1]))
How do I perform the arithmetic?
We can sort a list in lexicographical order using a custom comparator. The following code implements a custom comparator and passes it to List's sort() method.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.
Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place.
lists = [[2, 3], [7, 8], [3, 5]]
lists.sort(key=lambda x: (x[0]/x[1]))
print(lists)
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