【问题标题】:Ordering a string by its substring numerical value in python在python中按其子字符串数值对字符串进行排序
【发布时间】:2015-11-18 22:09:56
【问题描述】:

我有一个字符串列表,需要使用两个子字符串作为 int 键按数字顺序排序。 显然使用 sort() 函数按字母顺序排列我的字符串,所以我得到 1,10,2... 这显然不是我想要的。

四处搜索我发现一个关键参数可以传递给sort() 函数,使用sort(key=int) 应该可以解决问题,但是作为我的关键子字符串而不是整个字符串会导致转换错误。

假设我的字符串是这样的:

test1txtfgf10
test1txtfgg2
test2txffdt3
test2txtsdsd1

我希望我的列表根据第一个整数和第二个整数按数字顺序排序,所以我会:

test1txtfgg2
test1txtfgf10
test2txtsdsd1
test2txffdt3

我想我可以提取整数值,只对它们进行排序,跟踪它们属于哪个字符串,然后对字符串进行排序,但我想知道是否有一种方法可以更高效、更优雅地完成这件事。

提前致谢

【问题讨论】:

  • Python 2 还是 3?我问的原因是 Python 2 有一个 cmp 参数。
  • 虽然您可以自己编写此代码,但您可能希望查看 PyPI 上一些非常好的“自然排序”库。除了更容易之外,他们还可能想到了您没有想到的边缘情况,或者以您不会费心的方式优化事物等等。

标签: python string sorting


【解决方案1】:

试试下面的

In [26]: import re

In [27]: f = lambda x: [int(x) for x in re.findall(r'\d+', x)]

In [28]: sorted(strings, key=f)
Out[28]: ['test1txtfgg2', 'test1txtfgf10', 'test2txtsdsd1', 'test2txffdt3']

这使用正则表达式(re module)查找每个字符串中的所有整数,然后使用compares the resulting lists。例如,f('test1txtfgg2') 返回[1, 2],然后将其与其他列表进行比较。

【讨论】:

    【解决方案2】:

    提取数字部分并使用它们进行排序

    import re
    
    d = """test1txtfgf10
    test1txtfgg2
    test2txffdt3
    test2txtsdsd1"""
    
    lines = d.split("\n")
    
    re_numeric = re.compile("^[^\d]+(\d+)[^\d]+(\d+)$")
    
    def key(line):
        """Returns a tuple (n1, n2) of the numeric parts of line."""
        m = re_numeric.match(line)
        if m:
            return (int(m.groups(1)), int(m.groups(2)))
        else:
            return None
    
    lines.sort(key=key)
    

    现在lines

    ['test1txtfgg2', 'test1txtfgf10', 'test2txtsdsd1', 'test2txffdt3']
    

    【讨论】:

      【解决方案3】:
      import re
      k = [
           "test1txtfgf10",
           "test1txtfgg2",
           "test2txffdt3",
           "test2txtsdsd1"
          ]
      
      tmp = [([e for e in re.split("[a-z]",el) if e], el) for el in k ]
      sorted(tmp, key=lambda k: tmp[0])
      tmp = [res for cm, res in tmp]
      

      【讨论】:

        猜你喜欢
        • 2013-04-15
        • 1970-01-01
        • 2022-11-25
        • 2012-10-14
        • 2014-10-28
        • 2012-11-26
        • 2014-01-05
        • 1970-01-01
        • 2019-05-08
        相关资源
        最近更新 更多