jakehallas
jakehallas

Reputation: 2506

Sorting list with strings & ints in numerical order

I'm currently dealing with the below list:

[['John', '1', '2', '3'], ['Doe', '1', '2', '3']]

I'm incredibly new to python, I'm wanting to order this list in numerical order (high - low) but maintain the string at the beginning of the list. Like this:-

[['John', '3', '2', '1'], ['Doe', '3', '2', '1']]

There will always be one name & integers there after.

I collect this list from a csv file like so:-

import csv

with open('myCSV.csv', 'r') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print(sorted(your_list))

Any help is much appreciated. Thanks in advance..

Upvotes: 0

Views: 151

Answers (1)

alecxe
alecxe

Reputation: 473803

Iterate over the list and sort only the slice of each sublist without the first item. To sort strings as numbers pass key=int to sorted. Use reverse=True since you need a reversed order:

>>> l = [['John', '1', '2', '3'], ['Doe', '1', '2', '3']]
>>>
>>> [[sublist[0]] + sorted(sublist[1:], key=int, reverse=True) for sublist in l]
[['John', '3', '2', '1'], ['Doe', '3', '2', '1']]

Upvotes: 2

Related Questions