如何在Python中对字母数字列表进行排序

3

我有一个列表,如下:

a = [["1", "ok", "na"], ["15", "asd", "asdasd"], ["100", "uhu", "plo"], ["10", "iju", "tlo"], ["ISC_1", "des", "det"], ["12", "asd", "assrg"], ["ARF", "asd", "rf"]]

我希望按照以下方式对此列表进行排序:
[['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['100', 'uhu', 'plo'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']]

我使用了a.sort()

结果如下:

[['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['100', 'uhu', 'plo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']]

请帮我解决如何在这种情况下进行排序。

可能可以回答你的问题:https://dev59.com/u2Ij5IYBdhLWcg3wmWC1 - augustoccesar
3个回答

6
你可以使用名为key的命名参数。
它接受一个函数,该函数返回排序函数应该按其比较项目的值。
sorted(a, key = lambda l: int(l[0]))

它能在Python2.7中工作吗?出现以下错误`>>> sort(a, key = lambda l: int(l[0]))Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> sort(a, key = lambda l: int(l[0])) NameError: name 'sort' is not defined` - Sandeep Lade
使用´a.sort(key = lambda l: int(l[0]))´或者´b=sorted(a, key = lambda l: int(l[0]))´ - Leonhard Triendl
它抛出了无效的字面量,使用基数10:'ISC_1'。 - Shanky
2
ISC应该放在最后还是最前?如果要放在最后:a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 99999) - Leonhard Triendl
我将更新我的问题 - Shanky
显示剩余3条评论

3
为了准备处理非数字值,您可以使用:
a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 99999)
# or
b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 99999)

查看非数字的最后一个或

a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 0)
# or
b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 0)

首先要看到它们


感谢您的回复。 我希望得到以下结果:[['1','ok','na'],['10','iju','tlo'],['12','asd','assrg'],['15','asd','asdasd'],['100','uhu','plo'],['ARF','asd','rf'],['ISC_1','des','det']],其中ARF排在第一位,ISC_1排在最后。 - Shanky

3
您可以使用自然排序键,这非常容易通过正则表达式re.split()进行设置。
import re
try:
    # fast string checking and conversion
    from fastnumbers import *
except:
    pass

def natural_sort_key_for_list_of_lists(sublist):
    return [int(element) if element.isdigit() else element
            for element in re.split("([0-9]+)",sublist[0])]
    # put whichever index of the sublist you want here ^

a = [["1", "ok", "na"],
     ["15", "asd", "asdasd"],
     ["100", "uhu", "plo"],
     ["10", "iju", "tlo"],
     ["ISC_1", "des", "det"],
     ["12", "asd", "assrg"],
     ["ARF", "asd", "rf"]]

a.sort(key=natural_sort_key_for_list_of_lists)

for l in a:
    print (l)

结果:

['1', 'ok', 'na']
['10', 'iju', 'tlo']
['12', 'asd', 'assrg']
['15', 'asd', 'asdasd']
['100', 'uhu', 'plo']
['ARF', 'asd', 'rf']
['ISC_1', 'des', 'det']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接