Thistle19
Thistle19

Reputation: 37

Python: sorting list of lists not functioning as intended

I am trying to sort the following list of lists by the first item of each list in ascending order:

framenos = [
    ['1468', '2877', 'Pos.:', 95],
    ['3185', '4339', 'Pos.:', 96],
    ['195', '1460', 'Pos.:', 97]
]

I am using the following to do so:

framesorted = sorted(framenos, key=lambda x: x[0]) #sort ranges by start numbers

Which gives:

[['1468', '2877', 'Pos.:', 95], ['195', '1460', 'Pos.:', 97], ['3185', '4339', 'Pos.:', 96]]

What's going wrong?

Upvotes: 0

Views: 52

Answers (2)

Will
Will

Reputation: 4469

Since the first element of each list is a string, is is sorting these numbers in alphabetical order. in order to sort these lists based on the integer value of the first element try casting to int:

framesorted = sorted(framenos, key=lambda x: int(x[0])) 

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121744

Your values are strings, so you are sorting lexicographically, not numerically. '1468' is sorted before '195' because '4' comes before '9' in the ASCII standard, just like 'Ask' would be sorted before 'Attribution'.

Convert your strings to numbers if you need a numeric sort:

framesorted = sorted(framenos, key=lambda x: int(x[0]))

Demo:

>>> framenos = [
...     ['1468', '2877', 'Pos.:', 95],
...     ['3185', '4339', 'Pos.:', 96],
...     ['195', '1460', 'Pos.:', 97]
... ]
>>> sorted(framenos, key=lambda x: int(x[0]))
[['195', '1460', 'Pos.:', 97], ['1468', '2877', 'Pos.:', 95], ['3185', '4339', 'Pos.:', 96]]
>>> from pprint import pprint
>>> pprint(_)
[['195', '1460', 'Pos.:', 97],
 ['1468', '2877', 'Pos.:', 95],
 ['3185', '4339', 'Pos.:', 96]]

Upvotes: 5

Related Questions