【问题标题】:How to sort alphanumeric list in python如何在python中对字母数字列表进行排序
【发布时间】:2018-04-09 02:23:56
【问题描述】:

我有一个列表

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

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

【问题讨论】:

标签: python list sorting


【解决方案1】:

您可以使用 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
  • 带有 'a.sort(key = lambda l: int(l[0]))' 或 'b=sorted(a,key = lambda l: int(l[0]))'
  • 如果我的列表是 a = [["1", "ok", "na"], ["15", "asd", "asdasd"], ["100" , "uhu", "plo"], ["10", "iju", "tlo"], ["ISC_1", "des", "det"]]
  • 它为 int() 以 10 为基数抛出无效文字:'ISC_1'
  • 您希望 ISC 发生什么?它应该最后还是第一个?如果它应该排在最后: a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 99999)
【解决方案2】:

要为非数字值做好准备,您可以使用

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
【解决方案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']

【讨论】:

    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2023-03-06
    • 2021-03-10
    • 2016-05-19
    相关资源
    最近更新 更多