Python中不同排序技术的差异
这些都是不同类型的排序技术,其行为方式非常不同。让我们研究一下哪种技术如何工作,以及使用哪种技术。
假设’ a ‘是一个numpy数组
- a.sort()
(i)对数组进行原地排序并返回None
(ii)返回类型为None
(iii)占用较少空间。不创建副本,因为它直接对原始数组排序
(iv)比排序(a)快
# Python code to sort an array in-place
# using a.sort
import numpy as np
# Numpy array created
a = np.array([9, 3, 1, 7, 4, 3, 6])
# unsorted array print
print('Original array:\n', a)
# Return type is None
print('Return type:', a.sort())
# Sorted array output
print('Original array sorted->', a)
OUTPUT: For a.sort()
Original array:
[9 3 1 7 4 3 6]
Return type: None
Original array sorted-> [1 3 3 4 6 7 9]
- sorted(a)
(i)从旧的列表中创建一个新列表并返回排序后的新列表
(ii)返回类型为列表
(iii)创建原数组的副本,然后进行排序,占用更多空间
(iv)比a.sort()慢
# Python code to create a sorted copy using
# sorted()
import numpy as np
# Numpy array created
a = np.array([9, 3, 1, 7, 4, 3, 6])
# unsorted array print
print('Original array:\n', a)
b = sorted(a)
# sorted list returned to b, b type is
# <class 'list'>
print('New array sorted->', b)
# original array no change
print('Original array->', a)
OUTPUT:a.sorted()
Original array:
[9 3 1 7 4 3 6]
New array sorted-> [1, 3, 3, 4, 6, 7, 9]
Original array-> [9 3 1 7 4 3 6]
- np.argsort(a)
(i)返回对数组进行排序的下标
(ii)返回类型为numpy数组
(iii)当返回一个新的已排序的下标数组时占用空间
# Python code to demonstrate working of np.argsort
import numpy as np
# Numpy array created
a = np.array([9, 3, 1, 7, 4, 3, 6])
# unsorted array print
print('Original array:\n', a)
# Sort array indices
b = np.argsort(a)
print('Sorted indices of original array->', b)
# To get sorted array using sorted indices
# c is temp array created of same len as of b
c = np.zeros(len(b), dtype = int)
for i in range(0, len(b)):
c[i]= a[b[i]]
print('Sorted array->', c)
OUTPUT:np.argsort(a)
Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]
- np.lexsort((b, a))
(i) 使用键序列执行间接排序
(ii) 先按a排序,再按b排序
(iii) 返回int类型ndarray的下标数组,按指定的axis对键进行排序
(iv) 占用空间,返回一个新的索引排序数组。
# Python code to demonstrate working of
# np.lexsort()
import numpy as np
# Numpy array created
a = np.array([9, 3, 1, 3, 4, 3, 6]) # First column
b = np.array([4, 6, 9, 2, 1, 8, 7]) # Second column
print('column a, column b')
for (i, j) in zip(a, b):
print(i, ' ', j)
ind = np.lexsort((b, a)) # Sort by a then by b
print('Sorted indices->', ind)
OUTPUT:np.lexsort((b, a))
column a, column b
9 4
3 6
1 9
3 2
4 1
3 8
6 7
Sorted indices-> [2 3 1 5 4 6 0]