在python中按字母数字对列表排序

2024-06-16 11:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

这将返回:

测试1 测试10 测试2 测试4 测试9 测试11 测试6 测试3

并应返回:

测试1 测试2 测试4 测试9 测试10 测试6 测试11 测试3

有人能帮我解决这个问题吗 提前谢谢你。在


Tags: lambdakey答案列表排序字母数字item
1条回答
网友
1楼 · 发布于 2024-06-16 11:34:20

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

>>> 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也可以,但是访问的是返回值的第0个元素(“test”),而不是第二个元素(数字)

^{pr2}$

看起来您的final conditional试图确保字符串包含一个数字组件,这是一个好主意,尽管检查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(" ")))

相关问题 更多 >