Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform arithmetic to sort a list of lists

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?

like image 444
cccczzz Avatar asked Aug 11 '17 05:08

cccczzz


People also ask

Can we sort list of lists in Java?

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.

How do you sort a list in numerical order in Python?

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.

How do you sort a list of lists based on length?

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.


1 Answers

lists = [[2, 3], [7, 8], [3, 5]]
lists.sort(key=lambda x: (x[0]/x[1]))
print(lists)
like image 119
Md. Rezwanul Haque Avatar answered Sep 17 '22 20:09

Md. Rezwanul Haque