通过固定第一个元素自定义对列表进行排序 [英] Custom sort a list by fixing the first element

查看:86
本文介绍了通过固定第一个元素自定义对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

[25, 35, 54, 70, 68, 158, 78, 11, 18, 12]

我想通过固定第一个元素来对列表进行排序,即:如果我修复了35个,则排序后的列表应类似于

I want to sort this list by fixing the first element i.e: if I fix 35 the sorted list should look like

[35, 54, 68, 70, 78, 158, 11, 12, 18, 25]

如果我将158固定为第一个元素,则排序后的列表应该看起来像

If I fix 158 as the first element the sorted list should look like

[158, 11, 12, 18, 25, 35, 54, 68, 70, 78]

基本上,我想修复第一个元素,其余的应该按排序顺序进行,如果找到的数字小于第一个元素,则不应将其放在第一个元素之前.在Python中是否有内置功能可用于此目的?

basically I want to fix the first element and the rest should be in sorted order, if there is a number that is lesser than the first element is found it should not go before first element. Is there a builtin function available for this in Python?

推荐答案

只需定义一个键函数,如:

Just define a key function like:

def sorter(threshold):
    def key_func(item):
        if item >= threshold:
            return 0, item
        return 1, item

    return key_func

这可以通过返回一个元组来实现,以使高于阈值的数字排序在低于阈值的数字之下.

This works by returning a tuple such that the numbers above threshold will sort below the numbers under the threshold.

data = [25, 35, 54, 70, 68, 158, 78, 11, 18, 12]
print(sorted(data, key=sorter(70)))

结果:

[70, 78, 158, 11, 12, 18, 25, 35, 54, 68]

这篇关于通过固定第一个元素自定义对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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