What would be the most efficient / clean way to deeply sort a multidimensional list in Python?

Example:
From this list:

list = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] 

I would like to:

 print list [[1, 1, 1], [2, 4, 9], [10, 11, 16]] 

Is this possible with the list.sort () function, or do I need to write a custom loop?

+4
source share
2 answers

Here's an example of smoothing, sorting, and then restoring nested lists, as suggested by @Inerdia in the comments above.

I tried to use generators and iterators where possible, but I'm sure there are smarter and more efficient ways to get the result!

 from itertools import izip l = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] # flatten the list and sort it f = sorted(inner for outer in l for inner in outer) # group it into 3s again using izip new_list = [list(l) for l in izip(*[iter(f)]*3)] 
+1
source
 >>> l = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] >>> L = sorted([sub[i] for sub in l for i in range(3)]) >>> print L [1, 1, 1, 2, 4, 9, 10, 11, 16] 

Now you can group L into groups of 3

0
source

Source: https://habr.com/ru/post/1379393/


All Articles