1. 程式人生 > >python中的列表及numpy數組排序

python中的列表及numpy數組排序

fun one tom ont merge numpy for core uil


一、列表排序
# 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數組排序