Swagat
Swagat

Reputation: 11

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?

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)

for this given input:

5654 3456 7215 7612 5463

I get the list as:

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

I want the output to be like:

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

How to get this output?

Upvotes: 0

Views: 597

Answers (3)

sahasrara62
sahasrara62

Reputation: 11228

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]]

Upvotes: 0

Sheldore
Sheldore

Reputation: 39052

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]]

Upvotes: 1

Alain T.
Alain T.

Reputation: 42143

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())

Upvotes: 1

Related Questions