1

How do I sort the list below?

My results was:

['10','11','12','7','8','9'],['1','2','3','4','5','6']]

Here's my code

lst= [['7','10','8','9','11','12'],['3','1','2','4','6','5']]

for i in lst:
    i.sort()
    print(i)
4
  • 2
    What is your desired output? Commented Dec 6, 2015 at 22:45
  • Just google how to sort list in python. ..you will find a lot of stuff about that topic Commented Dec 6, 2015 at 22:46
  • @BrianCain asks a perfectly reasonable question: what is wrong with the output you got? Seems to me like your were sorting strings and you got the expected output from sorting those strings. Nothing obvious worng with that. You'll have to tell us what the problem is. Commented Dec 6, 2015 at 22:48
  • think about it for a second, you got a list with 2 lists within it right? to access the first one you'd do lst[0] and to access the other lst[1]... I leave the rest for you. Commented Dec 6, 2015 at 22:52

2 Answers 2

2

Use sorted(list, key=int):

lst= [['7','10','8','9','11','12'],['3','1','2','4','6','5']]

for i in lst:
    i = sorted(i, key=int)
    print(i)
Sign up to request clarification or add additional context in comments.

1 Comment

Fine, don't know that before :)
1

These are string objects, for string:

'10' < '7' because `1 < 7`

I think you want:

>>> [sorted(map(int, i)) for i in lst]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
>>> 

Just covert them to int objects before sort.


If you need keep them in string object, covert them back or set a key:

>>> [list(map(str, i)) for i in [sorted(map(int, i)) for i in lst]]
[['7', '8', '9', '10', '11', '12'], ['1', '2', '3', '4', '5', '6']]

>>> [sorted(i, key=lambda x: int(x)) for i in lst]
[['7', '8', '9', '10', '11', '12'], ['1', '2', '3', '4', '5', '6']]

1 Comment

This is giving me: [[7, 8, 9, 10, 11, 12], [1, 2, 3, 4, 5, 6]] not [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.