锲子
在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.
"""
pass
通过源码注释以及日常使用的经验,可以总结一下表格&#x