# ctfshow--web入門--文件上傳 [TOC](目錄標題) ## web151(前端校驗) 題目中提示前端檢驗不可靠,應該對前端檢驗進行繞過 
Parameters:
- aarray_like
-
Array to sort.
- axis int or None, optional
-
Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
- kind {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
-
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0.: The ‘stable’ option was added.
- 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:
- index_arrayndarray, int
-
Array of indices that sort a along the specified axis. If a is one-dimensional,
a[index_array]
yields a sorted a. More generally,np.take_along_axis(a, index_array, axis=axis)
always yields the sorted a, irrespective of dimensionality.
我們知道,argsort可以將數組進行排序,返回是排序後的索引,但是預設是按照從小到大排序的,然後通常做法是將其逆序回來。
test = np.array([1,0,0,1,1,1,1,1,0,0,2,2,2,0,0,0,1,0,0,1,1,1]) print (np.argsort(test)[-1])
這裡有幾個問題:
1. 預設argsort用的是quicksort排序演算法,這種方式排序是不穩定的。對穩定的排序演算法來說,每次排序結果都一樣,而且相同的兩個元素,先出現的還是排在前面。
2. 取-1逆序,會打亂數組的順序。
為什麼呢?
可以從argsort的參數看一下,尤其是kind 這個參數這裡,預設是quicksort,這個是不穩定的。而對stable, mergesort兩個用的都是timsort方法,這種方法是世界上最快的演算法,是結合了插入排序和歸併排序穩定的排序演算法,並做了許多優化, 在實際應用中效率很高。而stable是後來版本才出現的,而mergsort是為了相容舊版本,那麼stable,mergesort兩種方法得到的結果應該是一樣的。
test = np.array([1,0,0,1,1,1,1,1,0,0,2,2,2,0,0,0,1,0,0,1,1,1]) print (np.argsort(test,kind='mergesort')[-1]) ##這樣做無法做到先出現的排在前面
result = np.argsort(test) result1 = np.argsort(test, kind='stable') result2 = np.argsort(test, kind='mergesort') print (result) print (result1) print (result2)
因此,如果你想得到的排序是穩定的,設置kind=stable或者mergesort就可以了,這樣能得到穩定的從小達大排序的索引號。但是如果你想得到的是從大到小的排序,又要是穩定演算法,是不可以直接逆序進行的,因為這樣你跑壞了先出現排在前面的原則。
那麼怎麼辦呢?
在排序時,對數組進行取負,然後直接用argsort進行排序,當然還是要kind=mergesort,這個時候是從大到小排序並且是穩定排序。
test = np.array([1,0,0,1,1,1,1,1,0,0,2,2,2,0,0,0,1,0,0,1,1,1]) print (np.argsort(test,kind='mergesort')[-1]) ##這樣做無法做到先出現的排在前面 print ((-test).argsort(kind='mergesort')) print (np.argsort(-test, kind='mergesort'))
如此一來就能得到穩定的從大到小排序,並且穩定的,先出現的排在前面。代碼中後面兩種方式一樣,這個是毋庸置疑的。
平時我們只關註排序,大概不會註意到中間的差異,但是當你做工程時,如果不註意這些細節是很難做到方便工程上使用的。因此,別看一個小小的函數,影響還是很大的。工程上穩定排序是肯定的,但是argsort預設不是穩定的,而且如果你想從大到小,不是直接逆序就能滿足的。
當然如果你想要一個直接進行從大到小排序好的數組,可以直接用numpy.sort即可,用法和argsort是一樣的。也是通過配置這些參數達到穩定的排序。要說對數據進行計算,還是numpy厲害,什麼功能都有,而且很好用。
一切都在細節中……
Sophie的世界,轉載請註明出處,謝謝。