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

时间:2017-10-27 13:03:21

标签: python list sorting

我有一个列表

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

请帮助我在这种情况下如何排序。

3 个答案:

答案 0 :(得分:6)

您可以使用key命名参数 它接受一个函数,该函数返回排序函数应该比较项目的值。

sorted(a, key = lambda l: int(l[0]))

答案 1 :(得分: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)

首先看到它们

答案 2 :(得分: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']