如何在Python中对部分编号列表进行排序? [英] How do I sort a list of section numbers in Python?

查看:811
本文介绍了如何在Python中对部分编号列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

书本部分通常以x.x.x编号,例如1.2.3. 如何对部分编号列表进行排序?

Book sections are usually numbered as x.x.x, such as 1.2.3. How do I sort a list of section numbers?

将节号存储为字符串列表.

Store section numbers as a list of strings.

# a list of strings, section numbers
ls = ['1.1', '1.10', '1.2', '1.2.3', '1.2.1', '1.9']    

lists = sorted([s.split('.') for s in ls], key=lambda x:map(int, x))    
# [['1', '1'], ['1', '2'], ['1', '2', '1'], ['1', '2', '3'], ['1', '9'], ['1', '10']]

r = ['.'.join(sublist) for sublist in lists]    
#['1.1', '1.2', '1.2.1', '1.2.3', '1.9', '1.10']

但是,我的预期结果是

['1.1', '1.10', '1.2', '1.2.1', '1.2.3', '1.9']

推荐答案

使用自定义比较函数将字符串转换为整数子列表.这些将正确排序而不会出现问题.

Use a custom compare function that converts the strings into sub-lists of integers. Those will sort correctly without problems.

In [4]: ls = ['1.1', '1.10', '1.2', '1.2.3', '1.2.1', '1.9']

In [5]: def section(s):
   ...:     return [int(_) for _ in s.split(".")]
   ...:

In [6]: sorted(ls, key=section)
Out[6]: ['1.1', '1.2', '1.2.1', '1.2.3', '1.9', '1.10']

这篇关于如何在Python中对部分编号列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆