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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值