Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort each list in a list of lists

Tags:

python

How can I sort the lists in the following nested list? Function sort works only on normal lists.

lst = [[123,3,12],[89,14,2],[901,4,67]]

Expected result:

[[3,12,123],[2,14,89],[4,67,901]] 
like image 859
NIk Avatar asked Jan 16 '21 13:01

NIk


People also ask

Can you sort nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.

How do you sort a double list in Python?

To sort a two-dimensional list in Python use the sort() list method, which mutates the list, or the sorted() function, which does not. Set the key parameter for both types using a lambda function and return a tuple of the columns to sort according to the required sort order.


4 Answers

This is a very straightforward way to do it without any packages (list comprehension)

lst_sort = [sorted(item) for item in lst]
like image 136
Stefan Avatar answered Oct 16 '22 14:10

Stefan


try this:

lst = [[123,3,12],[89,14,2],[901,4,67]]

for element in lst:
    element.sort()

print(lst)

Loop through each item and sort separately.

like image 21
Jack Dane Avatar answered Oct 16 '22 13:10

Jack Dane


Here's a functional way to achieve this using map() with sorted() as:

>>> lst = [[123,3,12],[89,14,2],[901,4,67]]

>>> list(map(sorted, lst))
[[3, 12, 123], [2, 14, 89], [4, 67, 901]]

To know more about these functions, refer:

  • map() document
  • sorted() document
like image 6
Moinuddin Quadri Avatar answered Oct 16 '22 14:10

Moinuddin Quadri


Just sort each sub list independently:

lst = [[123,3,12],[89,14,2],[901,4,67]]
lst = [sorted(sub) for sub in lst]
like image 5
quamrana Avatar answered Oct 16 '22 13:10

quamrana