How do I organize each position on my list in ascending order?

Asked

Viewed 246 times

3

This is my code:

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

for i in range(0, len(a)):
    for j in range(0, len(a[i])):
        a[i].sort()

 print(a)

The problem is that it is only organizing the first position. Someone could give me an orientation?

4 answers

4

Simply do:

def ordena_lista(lista):
    for item in lista:
        item.sort()

The method sort() acts directly on the list by modifying the object without creating it again.

>>> lista = [[1, 4, 3, 2], [3, 2, 1]]
>>> ordena_lista(lista)
>>> lista
[[1, 2, 3, 4], [1, 2, 3]]

3

As a complement to what has already been said, it can also do the sort it wants using list compreehension that stays in a line:

a = [sorted(lista) for lista in a]
print(a) # [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

In this case I used the sorted instead of sort to return the sorted sub-list and assign to the correct element.

As @Andersoncarloswoss commented, the sorted returns a new sorted list instead of modifying the original, in contrast to the sort which changes the original. In case as the result was assigned again on a was in the same only with the new ordered list, but if it had other variables that refer to the original list it would remain intact.

A clearer example of this effect would be:

>>> x = [5, 1, 2, 4]
>>> y = sorted(x)
>>> x
[5, 1, 2, 4]
>>> y
[1, 2, 4, 5]

See this example in Ideone

2


All the answers solve the problem, but the answer given by @Thiago Magalhães is the one that most relates to my doubt.

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

  for i in range(0, len(a)):
       a[i].sort()
  print(a)

1

If you are not going to use the cluttered list it is good you use the method list.sort() instead of sorted(list), Because as has already been said here, the second creates a new list, so you will be using memory for nothing. In this case too it is not good not to use list compreehension, as it will use unnecessary memory in the same way, when mapping the null output of list.sort() in a new list. So, the simplest, quickest and most economical way to do this is:

for lista in listas:
   lista.sort()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.