代码之家  ›  专栏  ›  技术社区  ›  Amit Rastogi

如何根据子字符串对python字符串列表进行排序

  •  0
  • Amit Rastogi  · 技术社区  · 7 年前

    我正在尝试按照下面的代码使用sorted方法对python列表进行排序。但是,排序没有正确进行。

    #sort using the number part of the string
    mylist = ['XYZ-78.txt', 'XYZ-8.txt', 'XYZ-18.txt'] 
    def func(elem):
        return elem.split('-')[1].split('.')[0]
    
    sortlist = sorted(mylist,key=func)
    for i in sortlist:
      print(i)
    
    The output is-
    XYZ-18.txt
    XYZ-78.txt
    XYZ-8.txt
    
    I was expecting output as- 
    XYZ-8.txt
    XYZ-18.txt
    XYZ-78.txt
    
    5 回复  |  直到 7 年前
        1
  •  1
  •   Gsk    7 年前

    #sort using the number part of the string
    mylist = ['XYZ-78.txt', 'XYZ-8.txt', 'XYZ-18.txt'] 
    def func(elem):
        return int(elem.split('-')[1].split('.')[0])
    
    sortlist = sorted(mylist,key=func)
    for i in sortlist:
      print(i)
    

    您看到的是基于ascii值密码的排序

        2
  •  1
  •   Rakesh    7 年前

    用int封装变量。

    前任:

    mylist = ['XYZ-78.txt', 'XYZ-8.txt', 'XYZ-18.txt'] 
    print(sorted(mylist, key=lambda x: int(x.split("-")[-1].split(".")[0])))
    

    输出:

    ['XYZ-8.txt', 'XYZ-18.txt', 'XYZ-78.txt']
    
        3
  •  0
  •   RomanPerekhrest    7 年前

    str 方法:

    mylist = ['XYZ-78.txt', 'XYZ-8.txt', 'XYZ-18.txt']
    result = sorted(mylist, key=lambda x: int(x[x.index('-')+1:].replace('.txt', '')))
    
    print(result)
    

    输出:

    ['XYZ-8.txt', 'XYZ-18.txt', 'XYZ-78.txt']
    
        4
  •  0
  •   noobron    7 年前

    使用此代码对字符串列表进行数字排序(这是必需的),而不是按字母顺序排序(这是在给定代码中发生的)。

    #sort using the number part of the string
    

    mylist=['xyz-78.txt','xyz-8.txt','xyz-18.txt'] 定义函数(elem): 返回elem[elem.index('-')+1:len(elem)-5] sortlist=已排序(mylist,key=func) 对于SortList中的I: 印刷品(一)

        5
  •  0
  •   user1767754    7 年前

    这个问题有一个通用的方法叫做 human readable sort 或者用更流行的名字 alphanum sort 基本上是按照人类期望的方式来分类。

    import re
    mylist = ['XYZ78.txt', 'XYZ8.txt', 'XYZ18.txt'] 
    
    def tryint(s):
        try:
            return int(s)
        except:
            return s
    
    def alphanum_key(s):
        """ Turn a string into a list of string and number chunks.
            "z23a" -> ["z", 23, "a"]
        """
        return [ tryint(c) for c in re.split('([0-9]+)', s) ]
    
    def sort_nicely(l):
        """ Sort the given list in the way that humans expect.
        """
    
    l.sort(key=alphanum_key)
    ['XYZ-8.txt', 'XYZ-18.txt', 'XYZ-78.txt']
    

    对任何一根绳子都有效,不用 分裂 用于提取可排序字段的字符。

    很好的阅读关于字母: http://www.davekoelle.com/alphanum.html

    原始源代码: https://nedbatchelder.com/blog/200712/human_sorting.html