如何对python中设置的字母数字集进行排序 [英] How to sort alpha numeric set in python
本文介绍了如何对python中设置的字母数字集进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一套
set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
排序后,我希望它看起来像
After sorting I want it to look like
4 sheets,
12 sheets,
48 sheets,
booklet
请问
推荐答案
又甜又甜:
sorted(data, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
此版本:
- 可在Python 2和Python 3中使用,因为:
- 它不假定您比较字符串和整数(在Python 3中不起作用)
- 它不对
sorted
使用cmp
参数(在Python 3中不存在)
- Works in Python 2 and Python 3, because:
- It does not assume you compare strings and integers (which won't work in Python 3)
- It doesn't use the
cmp
parameter tosorted
(which doesn't exist in Python 3)
如果您要完全按照示例中的说明打印输出,则:
If you want printed output exactly as described in your example, then:
data = set(['booklet', '4 sheets', '48 sheets', '12 sheets']) r = sorted(data, key=lambda item: (int(item.partition(' ')[0]) if item[0].isdigit() else float('inf'), item)) print ',\n'.join(r)
这篇关于如何对python中设置的字母数字集进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文