如何在Python中使用自定义谓词排序 [英] How to use a custom predicate sort with Python

查看:123
本文介绍了如何在Python中使用自定义谓词排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如[[1,2,"s"],[1,5,"e"],...],其中第三个值始终是se.如何调用sort(),以使列表根据以下条件进行排序:

I have a list of lists like [[1,2,"s"],[1,5,"e"],...] where the 3rd value is always either s or e. How can I call sort() such that the list is sorted based on:

  1. 第一个索引
  2. 如果第一个索引相同,则s首先.
  1. the first index
  2. if the first index is same, s comes first.

谢谢

推荐答案

编写自定义key函数.

def sort_key(list_):
    if list_[2] == 's':
        return (list_[0], 0)
    return (list_[0], 1)

test_list = [[1, 2, 's'], [1, 5, 'e'], [2, 4, 'e'], [2, 3, 's']]
test_list.sort(key=sort_key)
# [[1, 2, 's'], [1, 5, 'e'], [2, 3, 's'], [2, 4, 'e']]

这篇关于如何在Python中使用自定义谓词排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆