I have lists like:
['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']
I want to sort them such that I always have the fields starting from "pt=" first and the rest of them sorted in alphabetical order.
so the result would be:
['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']
How do I go about this?
解决方案
Return a tuple per item:
sorted(yourlist, key=lambda x: (not x.startswith('pt='), x))
This will sort any value starting with pt= first (as False sorts before True), any other value is sorted lexicographically (which means the same as alphabetical when applied to text).
Demo:
>>> 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']