【问题标题】:Sorting list with rules with python使用python的规则排序列表
【发布时间】:2020-09-16 21:54:57
【问题描述】:

我有一个这样的列表

['File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5', 'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6']

当我在 python 中使用sorted() 对其进行排序时。会变成这样:

['File007', 'File1', 'File10', 'File11', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File8', 'File8b1', 'File8b11', 'File8b2', 'File9']

但我想要的是:

['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']

它必须是数字排序: 文件1、文件2、文件3、文件10

不喜欢: 文件1、文件10、文件2、文件3

如果像这个 File007 有 0 位,则算作 7

如果它在数字后有字母,例如 File3a,它将像这样排序: 文件 3、文件 3a、文件 3b、...

有没有办法在列表排序中添加此规则?

【问题讨论】:

    标签: python sorting arraylist


    【解决方案1】:

    是的,您可以使用在排序过程中运行的函数

    # Sort a list based on removing leading zeros
    def mysort(x): 
        return int(str(x).replace("0",""))
    
    L = ["002", "013", "001", "005"] 
    
    print ("Normal sorting :", sorted(L)) 
    print ("Sorted with key:", sorted(L, key = mysort)) 
    

    【讨论】:

      【解决方案2】:

      有一种方法可以定义您自己的排序规则,方法是将key 关键字参数传递给sorted 函数。一些似乎完全符合您要求的代码可能如下所示:

      import re
      
      def key_fn(f):
          # the f[4:] part just gets the part of each string after 'File'
          groups = re.match(r'(\d*)(\D*)(\d*)', f[4:]).groups()
          def try_parse_int(x):
              # x should be either an empty string or something we can
              # parse into an int
              try:
                  return int(x)
              except ValueError:
                  return None
          return try_parse_int(groups[0]), groups[1], try_parse_int(groups[2])
      
      files = ['File3','File007','File3a','File10','File11','File1','File4','File5',
          'File9','File8','File8b1','File8b2','File8b11','File6']
      
      sorted_files = sorted(files, key=key_fn)
      

      这支持任意数量的数字,后跟(可选)任意数量的非数字,再后跟(可选)任意数量的数字。

      【讨论】:

      • 您可能希望转换为由数字组成的整数组。
      猜你喜欢
      • 2022-08-08
      • 2014-03-12
      • 2021-08-24
      • 2021-09-10
      • 2013-01-13
      • 2019-11-08
      • 2011-02-13
      • 2015-10-09
      • 2017-07-09
      相关资源
      最近更新 更多