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

2

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 you are only organizing the first position. Could someone give me an orientation?

    
asked by anonymous 04.08.2018 / 04:15

4 answers

1

All 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)
    
29.08.2018 / 04:08
4

Simply do:

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

The sort() method 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]]
    
04.08.2018 / 04:59
3

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

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

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

Just like @AndersonCarlosWoss commented, sorted returns a new ordered list instead of modifying the original, in contrast to the sort that changes the original. In case the result was reassigned over a it remained the same only with the new ordered list, but if it had other variables referring 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

    
04.08.2018 / 11:28
1

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

for lista in listas:
   lista.sort()
    
04.08.2018 / 16:29