在python中通过其子字符串数值排序字符串

时间:2015-05-20 08:19:11

标签: python string sorting

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

搜索我发现一个关键参数可以传递给sort()函数,并且使用sort(key=int)应该可以做到这一点,但是作为我的关键字是一个子字符串而不是整个字符串应该导致一个演员表错误。

假设我的字符串类似于:

test1txtfgf10
test1txtfgg2
test2txffdt3
test2txtsdsd1

我希望我的列表按照第一个整数然后在第二个整数的数字顺序排序,所以我会:

test1txtfgg2
test1txtfgf10
test2txtsdsd1
test2txffdt3

我想我可以提取整数值,只对它们进行排序,跟踪它们属于哪个字符串,然后对字符串进行排序,但我想知道是否有办法以更有效和更优雅的方式做这件事。 / p>

提前致谢

3 个答案:

答案 0 :(得分:4)

尝试以下

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],然后将其与其他列表进行比较。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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]
相关问题