0

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..

1
  • There are no integers in that list anywhere, only (lists of) strings. Commented Feb 18, 2016 at 19:39

1 Answer 1

2

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']]
Sign up to request clarification or add additional context in comments.

2 Comments

Changing [sublist[0]] to sublist[:1] would look nicer.
Thank you very much! I will accept the answer when it lets me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.