Home > database >  How can I sort the lists in the list?
How can I sort the lists in the list?

Time:10-08

I'd like to know how to sort the lists in the list. However, I don't want to align by key. I'd like to change it according to the following method.

arr = [[2, 3], [5, 1], [4, 1], [5, 3], [4, 2]]
# solution...
I_want_arr = [[2, 3], [1, 5], [1, 4], [3, 5], [2, 4]]

i tried it

for i in graph:
  i.sort()

but, it didn't work

CodePudding user response:

using list comprehenstion:

arr = [[2, 3], [5, 1], [4, 1], [5, 3], [4, 2]]
sorted_output = [sorted(l) for l in arr]

using map():

sorted_output = list(map(sorted, arr))

CodePudding user response:

@Gabip's solution includes this and a more time efficient one, check that out first!

How about

arr = [[2, 3], [5, 1], [4, 1], [5, 3], [4, 2]]

I_want_arr = [sorted(x) for x in arr]

This outputs

[[2, 3], [1, 5], [1, 4], [3, 5], [2, 4]]
  • Related