简体   繁体   English

字符串和整数按数字顺序排序的列表

[英]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. 我是python的新手,我想按数字顺序(高-低)对列表进行排序,但要将字符串保留在列表的开头。 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:- 我从这样的csv文件收集此列表:-

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.. 提前致谢..

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. 要将字符串作为数字进行排序,请通过key=int进行排序。 Use reverse=True since you need a reversed order: 使用reverse=True因为您需要reverse=True订单:

>>> 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM