【发布时间】:2021-12-21 05:07:10
【问题描述】:
我有一个字符串列表,其中包含由点 . 分隔的命令,如下所示:
DeviceA.CommandA.1.Hello,
DeviceA.CommandA.2.Hello,
DeviceA.CommandA.11.Hello,
DeviceA.CommandA.3.Hello,
DeviceA.CommandB.1.Hello,
DeviceA.CommandB.1.Bye,
DeviceB.CommandB.What,
DeviceA.SubdeviceA.CommandB.1.Hello,
DeviceA.SubdeviceA.CommandB.2.Hello,
DeviceA.SubdeviceB.CommandA.1.What
我想按自然顺序排列它们:
- 顺序必须按字段索引优先(例如,以 DeviceA 开头的命令将始终排在 DeviceB 之前等)
- 按字母顺序排列字符串
- 当它找到一个按数字升序排序的数字时
因此,排序后的输出应该是:
DeviceA.CommandA.1.Hello,
DeviceA.CommandA.2.Hello,
DeviceA.CommandA.3.Hello,
DeviceA.CommandA.11.Hello,
DeviceA.CommandB.1.Bye,
DeviceA.CommandB.1.Hello,
DeviceA.SubdeviceA.CommandB.1.Hello,
DeviceA.SubdeviceA.CommandB.2.Hello,
DeviceA.SubdeviceB.CommandA.What,
DeviceB.CommandB.What
还要注意命令字段的长度是动态的,以点分隔的字段数可以是任意大小。
到目前为止,我试过这个没有运气(数字按字母顺序排列,例如 11 在 5 之前):
list = [
"DeviceA.CommandA.1.Hello",
"DeviceA.CommandA.2.Hello",
"DeviceA.CommandA.11.Hello",
"DeviceA.CommandA.3.Hello",
"DeviceA.CommandB.1.Hello",
"DeviceA.CommandB.1.Bye",
"DeviceB.CommandB.What",
"DeviceA.SubdeviceA.CommandB.1.Hello",
"DeviceA.SubdeviceA.CommandB.2.Hello",
"DeviceA.SubdeviceB.CommandA.1.What"
]
sorted_list = sorted(list, key=lambda x: x.split('.'))
编辑:更正了拼写错误。
【问题讨论】:
标签: python python-2.7 sorting split