【问题标题】:Sort lists in python based on a rule根据规则对python中的列表进行排序
【发布时间】:2014-03-12 19:11:51
【问题描述】:

我有如下列表:

['pt=media:song', 'class=song', 'object=mp3']
['class=text','pt=transaction:email', 'object=email']
['category=where','pt=text:where','class:question']
['object:mp4','class=movie', 'pt=media:movie']

我想对它们进行排序,以便我始终将字段从 "pt=" 开始,其余的按字母顺序排序。

所以结果是:

['pt=media:song','class=song', 'object=mp3']
['pt=transaction:email','class=text', 'object=email']
['pt=text:where','category=where','class:question'] 
['pt=media:movie','class=movie','object:mp4']

我该怎么做?

【问题讨论】:

  • 您的列表中没有日期或其他任何内容。在这种情况下,“时间顺序”到底是什么意思?
  • 您的示例输出使用升序字典序顺序。对于文本,这是按字母顺序排列的。

标签: python list sorting python-2.7


【解决方案1】:

每个项目返回一个元组:

sorted(yourlist, key=lambda x: (not x.startswith('pt='), x))

这将对任何以pt= 开头的值进行排序(因为FalseTrue 之前排序),任何其他值都按字典顺序排序(这意味着在应用于文本时与字母顺序相同)。

演示:

>>> samples = [
...     ['pt=media:song','class=song', 'object=mp3'],
...     ['class=text','pt=transaction:email', 'object=email'],
...     ['category=where','pt=text:where','class:question'],
...     ['object:mp4','class=movie', 'pt=media:movie'],
... ]
>>> for sample in samples:
...     print sorted(sample, key=lambda x: (not x.startswith('pt='), x))
... 
['pt=media:song', 'class=song', 'object=mp3']
['pt=transaction:email', 'class=text', 'object=email']
['pt=text:where', 'category=where', 'class:question']
['pt=media:movie', 'class=movie', 'object:mp4']

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多