如何在python中对列表套列表进行排序,在Python中对列表列表进行排序

c2=[]

row1=[1,22,53]

row2=[14,25,46]

row3=[7,8,9]

c2.append(row2)

c2.append(row1)

c2.append(row3)

c2 is now:

[[14, 25, 46], [1, 22, 53], [7, 8, 9]]

how do i sort c2 in such a way that for example:

for row in c2:

sort on row[2]

the result would be:

[[7,8,9],[14,25,46],[1,22,53]]

the other question is how do i first sort by row[2] and within that set by row[1]

解决方案

The key argument to sort specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambda that returns the last element from each row to be used in the sort:

c2.sort(key = lambda row: row[2])

A lambda is a simple anonymous function. It's handy when you want to create a simple single use function like this. The equivalent code not using a lambda would be:

def sort_key(row):

return row[2]

c2.sort(key = sort_key)

If you want to sort on more entries, just make the key function return a tuple containing the values you wish to sort on in order of importance. For example:

c2.sort(key = lambda row: (row[2],row[1]))

or:

c2.sort(key = lambda row: (row[2],row[1],row[0]))

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值