天天看點

python漢字排序規則_根據規則對python中的清單進行排序

傳回每個項目的元組:

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