锲子
在Python开发的过程中,我们经常使用到.sort()和sorted()方法,但你知道这两者使用的差别么?
在文章的开始,我来提出几个问题考考大家,看看大家对下面6个问题是否都清楚、明白。
-
sorted()可以排序字符串么 ? 比如 sorted(‘adbc’)
-
.sort()方法是否可以作用于集合与字典?
-
arr = [('a', 1), ('b', 5), ('a', 3), ('b', 4)]如何按照列表元素的字符升序和数字降序进行排列? -
什么叫做 stable 稳定排序?
-
对上述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) -
你是否了解 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.
"""

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

被折叠的 条评论
为什么被折叠?



