Skip to content Skip to sidebar Skip to footer

How To Sort A List Nested Inside Another List?

I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

Solution 1:

You can use map for this:

n_list = list(map(sorted, n_list))

or directly:

n_list = list(map(lambda n:sorted(map(int,n)), input().split())

Solution 2:

Try a list comprehension where you map your strings to integers and then sort them using sorted

num = ['5654', '3456', '7215', '7612', '5463']
answer = [sorted(map(int, i)) for i in num]
# [[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

Solution 3:

inp = '5654 3456 7215 7612 5463'# user input
res= [] # list to store the final output# iterating over each number which is divided into a list via inp.split()for i in inp.split():
    # keeping internal list which will keep the each digit in int format
    tmp=[]
    for j in i: # iterating over the number eg 5654# converting each digit to int and adding it to temp list
         tmp.append(int(j))
    # sorting internal list and appending it to final result list
    res.append(sorted(tmp)) 

print(res) # printing final list

output

[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

Post a Comment for "How To Sort A List Nested Inside Another List?"