如何对python中的字母数字集进行排序 [英] How to sort alpha numeric set in python

查看:38
本文介绍了如何对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 中不起作用)
    • 它不使用 cmp 参数来sorted(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 to sorted (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 ',
      '.join(r)
      

      这篇关于如何对python中的字母数字集进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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