python排列整数,Python排序列表的列表包含整数和内部带有整数的字符串

How i can use python to sort the list format

format=["12 sheet","4 sheet","48 sheet","6 sheet", "busrear", "phonebox","train"]

like this way

format =["4 sheet", "6 sheet", "12 sheet", "48 sheet", "busrear", "phonebox", "train"]

but If the array is a list of list then how can we do that like this one

format=[[1, '12 sheet', 0],[2, '4 sheet', 0], [3, '48 sheet', 0], [4, '6 sheet', 0 [5, 'Busrear', 0], [6, 'phonebox', 0], [7, 'train', 0]]

I Need the result to be like this

format=[[2, '4 sheet', 0],[4, '6 sheet', 0],[1, '12 sheet', 0],[3, '48 sheet', 0],[5, 'Busrear', 0], [6, 'phonebox', 0], [7, 'train', 0]]

解决方案

You can do this:

lst = [[1L, u'12 sheet', 0],

[2L, u'4 sheet', 0],

[3L, u'48 sheet', 0],

[4L, u'6 sheet', 0],

[5L, u'Busrear', 0],

[6L, u'phonebox', 0],

[7L, u'train', 0]]

def sortby(x):

try:

return int(x[1].split(' ')[0])

except ValueError:

return float('inf')

lst.sort(key=sortby)

print lst

Output:

[[2L, u'4 sheet', 0], [4L, u'6 sheet', 0], [1L, u'12 sheet', 0], [3L, u'48 sheet', 0], [5L, u'Busrear', 0], [6L, u'phonebox', 0], [7L, u'train', 0]]

You can always use fancier list comprehension but readability counts. Which is why you might not feel like modifying the cool solution by falsetru for this slightly changed task.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值