python中的列表及numpy数组排序

Posted 贝壳w

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中的列表及numpy数组排序相关的知识,希望对你有一定的参考价值。


一、列表排序 
# python中对列表排序有sort、sorted两种方法,其中sort是列表内置方法,其帮助文档如下:
In [1]: help(sorted) Help on built-in function sorted in module builtins: sorted(iterable, /, *, key=None, reverse=False) 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. In [2]: help(list.sort) Help on method_descriptor: sort(...) L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
# 一维列表排序
a = [2,1,4,3,5]
a.sort() #[1, 2, 3, 4, 5]
a.sort(reverse=True) #[5, 4, 3, 2, 1]
# sorted()用法同sort(),不同点在于sorted()方法不影响原列表元素的顺序
a = [2,1,4,3,5]
b = sorted(a) # b: [1, 2, 3, 4, 5]
a # a: [2, 1, 4, 3, 5]
# 二维列表排序
# 二维列表排序,可以设置sort()和sorted()方法的key关键字,通过lambda函数指定排序关键字
a = [[1,‘b‘,5],[3,‘c‘,3],[5,‘a‘,4],[4,‘d‘,1],[2,‘f‘,2]]
a.sort(key=(lambda x:x[0])) # [[1, ‘b‘, 5], [2, ‘f‘, 2], [3, ‘c‘, 3], [4, ‘d‘, 1], [5, ‘a‘, 4]]
a.sort(key=(lambda x:x[1])) # [[5, ‘a‘, 4], [1, ‘b‘, 5], [3, ‘c‘, 3], [4, ‘d‘, 1], [2, ‘f‘, 2]]
a.sort(key=(lambda x:x[0]),reverse=True) # reverse=True 按照x[0]降序排列 [[5, ‘a‘, 4], [4, ‘d‘, 1], [3, ‘c‘, 3], [2, ‘f‘, 2], [1, ‘b‘, 5]]

二、numpy数组排序

# numpy.sort()
In [3]: help(np.sort) Help on function sort in module numpy.core.fromnumeric: sort(a, axis=-1, kind=quicksort, order=None) Return a sorted copy of an array. Parameters ---------- a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {quicksort, mergesort, heapsort}, optional Sorting algorithm. Default is quicksort. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`.
In [4]: a
Out[1]:
array([[1, b, 5],
       [3, c, 3],
       [5, a, 4],
       [4, d, 1],
       [2, f, 2]], dtype=<U11)

In [5]: np.sort(a,axis=0)  # axis=0 按列跨行排序
Out[2]:
array([[1, a, 1],
       [2, b, 2],
       [3, c, 3],
       [4, d, 4],
       [5, f, 5]], dtype=<U11)

In [6]: np.sort(a,axis=1)  # axis=1 按行跨列排序
Out[3]:
array([[1, 5, b],
       [3, 3, c],
       [4, 5, a],
       [1, 4, d],
       [2, 2, f]], dtype=<U11)

numpy中还有ndarray.sort()、argsort()和lexsort()方法,用到后再学习记录,待续……

















以上是关于python中的列表及numpy数组排序的主要内容,如果未能解决你的问题,请参考以下文章

乐哥学AI_Python:Numpy索引,切片,常用函数

NumPy常用函数——构造数组函数及代码示例

python 二维数组排序

我如何“压缩排序”并行numpy数组?

python常用序列listtuples及矩阵库numpy的使用

Python中numpy.array函数有什么作用呢?