siwookJeong
siwookJeong

Reputation: 33

How can I sort the lists in the list?

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 arr:
  i.sort()

but, it didn't work

Upvotes: 0

Views: 122

Answers (2)

mikelsr
mikelsr

Reputation: 457

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

Upvotes: 2

Gabio
Gabio

Reputation: 9494

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

Upvotes: 9

Related Questions