[面试热点]深挖那些隐藏在sort和sorted背后的知识!

本文深入探讨Python的.sort()和sorted()方法,包括默认排序、条件排序、稳定排序的概念,以及cmp_to_key的使用。通过实例解析排序的细节,并解答相关面试问题,如排序字符串、数字与字母组合的排序等。同时,介绍了使用cmp_to_key解决LeetCode 179题的最大数问题,提供冒泡排序和cmp_to_key两种解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

锲子

在Python开发的过程中,我们经常使用到.sort()和sorted()方法,但你知道这两者使用的差别么?

在文章的开始,我来提出几个问题考考大家,看看大家对下面6个问题是否都清楚、明白。

  1. sorted()可以排序字符串么 ? 比如 sorted(‘adbc’)

  2. .sort()方法是否可以作用于集合与字典?

  3. arr = [('a', 1), ('b', 5), ('a', 3), ('b', 4)] 如何按照列表元素的字符升序和数字降序进行排列?

  4. 什么叫做 stable 稳定排序?

  5. 对上述arr列表,以下四种排序的结果一样么?

    arr = [('a', 1), ('b', 4), ('a', 2), ('b', 3)]
    # 第一种
    print(sorted(arr, key=lambda x: [x[0], -x[1]]))
    # 第二种
    print(sorted(sorted(arr, key=lambda x: x[0]), key=lambda x: -x[1]))
    # 第三种
    arr.sort(key=lambda x: [x[0], -x[1]])
    print(arr)
    # 第四种
    arr.sort(key=lambda x: x[0])
    arr.sort(key=lambda x: -x[1])
    print(arr)
    
  6. 你是否了解 cmp_to_key 方法的使用 ?

sort和sorted的介绍

今天我来带大家,深入了解 .sort()和sorted()方法,有哪些不为人知的细节!

首先,我们来看看Python代码中,这两个方法的注释和所处的位置。

以下内容,来自Python源码:

# sort
class list(object):   
    def sort(self, *args, **kwargs): # real signature unknown
        """
        Sort the list in ascending order and return None.
        
        The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
        order of two equal elements is maintained).
        
        If a key function is given, apply it once to each list item and sort them,
        ascending or descending, according to their function values.
        
        The reverse flag can be set to sort in descending order.
        """
        pass
    
# sorted
def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass

通过源码注释以及日常使用的经验,可以总结一下表格&#x

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值