Rotan075
Rotan075

Reputation: 2615

Sorting lists based on first integer

I got a problem regarding sorting a list within Python. For some reason it does rank the list on the highest value but after that process is done, other elements within that list are not sorted anymore.

My code:

import csv

id_list = []

with open('source/to/file/output.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',', quotechar='"')
    for row in reader:
        test = "177"
        if test == row[0]:
            id_list.append([row[2],row[1]])            

generated_list = id_list[0], id_list[16], id_list[20]

print(generated_list)
print(sorted(generated_list))

The result of the print is:

-- (['17', '179'], ['5', '2641'], ['9', '3705']) # not sorted
-- [['17', '179'], ['5', '2641'], ['9', '3705']] # sorted

What I would expect is that the sorting method will output:

-- [['17', '179'], ['9', '3705'], ['5', '2641']] # sorted

Am I doing something wrong?

Upvotes: 0

Views: 185

Answers (1)

Kasravnd
Kasravnd

Reputation: 107337

Python sort your lists based on first element lexicographicaly because you have string, for get ride of that use a key function to sort based on int value :

print(sorted(generated_list,key=lambda x:int(x[0]),reverse=True))

Demo :

>>> sorted(generated_list,key=lambda x:int(x[0]),reverse=True)
[['17', '179'], ['9', '3705'], ['5', '2641']]

Or as says in comment you can convert your number to integer before sorting,also you can unpack your rows for refuse multiple indexing :

with open('source/to/file/output.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',', quotechar='"')
    for row in reader:
        test = "177"
        row1,row2,row3=row
        if test == row1:
            id_list.append([int(row2),row(row1)])

Upvotes: 3

Related Questions