根据规则对python中的列表进行排序

时间:2014-02-13 18:10:07

标签: python list sorting python-2.7

我有以下列表:

['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']

我该怎么做?

1 个答案:

答案 0 :(得分:5)

每个项目返回一个元组:

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

这将首先排序以pt=开头的任何值(False之前的True排序),任何其他值按字典顺​​序排序(这意味着应用于文本时按字母顺序排列)

演示:

>>> 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']