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

use*_*851 1 python sorting list 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']
Run Code Online (Sandbox Code Playgroud)

我想对它们进行排序,使得我总是从"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']
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Mar*_*ers 5

每个项目返回一个元组:

sorted(yourlist, key=lambda x: (not x.startswith('pt='), x))
Run Code Online (Sandbox Code Playgroud)

这将对从pt=first 开始的任何值进行排序(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']
Run Code Online (Sandbox Code Playgroud)