1

我是 python 新手,我正在尝试对列表字母数字进行排序。

我在这里看到了其他答案并试图自己弄清楚,但可以解决这个问题!

假设我有这个列表:

showslist = ("Atest 2", "Atest 4", "Atest 1", "Atest 9", "Atest 10", "Btest 11", "Btest 6", "Ctest 3")

sortfiles = sorted(showslist, key=lambda item: (int(item.partition(' ')[0])
                                   if item[0].isdigit() else float('inf'), item))
for i in sortfiles:
    print i

这返回:

Atest 1 Atest 10 Atest 2 Atest 4 Atest 9 Btest 11 Btest 6 Ctest 3

并且应该返回:

Atest 1 Atest 2 Atest 4 Atest 9 Atest 10 Btest 6 Btest 11 Ctest 3

任何人都可以帮我解决这个问题,请提前非常感谢。

4

1 回答 1

1

在空格上拆分项目,取后半部分,将其转换为整数,然后使用它进行排序。

>>> showslist = ("test 2", "test 4", "test 1", "test 9", "test 10", "test 11", "test 6", "test 3")
>>> sorted(showslist, key=lambda item: int(item.split()[1]))
['test 1', 'test 2', 'test 3', 'test 4', 'test 6', 'test 9', 'test 10', 'test 11']

partition也可以,但是您访问的是返回值的第零个元素(“test”),而不是第二个(数字)。

>>> sorted(showslist, key=lambda item: int(item.partition(' ')[2]))
['test 1', 'test 2', 'test 3', 'test 4', 'test 6', 'test 9', 'test 10', 'test 11']

看起来您的最终条件是试图确保字符串完全具有数字分量,这是一个好主意,尽管在item这里检查第 0 个字符是数字对您没有多大好处,因为那是“t”对于您展示的所有项目。

>>> showslist = ("test 2", "test 4", "oops no number here", "test 3")
>>> sorted(showslist, key=lambda item: int(item.partition(' ')[2]) if ' ' in item and item.partition(' ')[2].isdigit() else float('inf'))
['test 2', 'test 3', 'test 4', 'oops no number here']

如果您想先按文本组件排序,然后按数字组件排序,您可以编写一个函数,该函数接受一个项目并返回一个 (text, number) 元组,Python 将按照您想要的方式对其进行排序。

def getValue(x):
    a,_,b = x.partition(" ")
    if not b.isdigit():
        return (float("inf"), x)
    return (a, int(b))

showslist = ("Atest 2", "Atest 4", "Atest 1", "Atest 9", "Atest 10", "Btest 11", "Btest 6", "Ctest 3")
print sorted(showslist, key=getValue)
#result: ['Atest 1', 'Atest 2', 'Atest 4', 'Atest 9', 'Atest 10', 'Btest 6', 'Btest 11', 'Ctest 3']

这可以在一行中完成,尽管您失去的可读性比获得的文件大小要多:

print sorted(showslist, key= lambda x: (lambda a, _, b: (a, int(b)) if b.isdigit() else (float("inf"), x))(*x.partition(" ")))
于 2013-11-06T20:18:22.967 回答