我正在嘗試對二維陣列進行排序,我嘗試了很多方法但它不起作用。我不知道這里發生了什么
from operator import itemgetter
import pprint
arr=[['0.55070000', '879.00000000'], ['0.55350000', '879.00000000'], ['0.55640000', '879.00000000'], ['0.56210000', '879.00000000'], ['0.56490000', '879.00000000'], ['0.56780000', '879.00000000'], ['0.57060000', '879.00000000'], ['0.54500000', '899.00000000'], ['0.56370000', '901.00000000'], ['0.53070000', '908.00000000'], ['0.57350000', '916.00000000'], ['0.55000000', '9172.00000000'], ['0.56300000', '939.00000000'], ['0.54490000', '94.00000000'], ['0.56040000', '96.00000000'], ['0.54960000', '999.00000000']]
# sorted(floatarry, key=itemgetter(1))
sorted(arr,key=lambda x:x[1])
pprint.pprint(arr)
# from operator import itemgetter
#############################################################
# columnIndex = 1
# # Sort 2D numpy array by 2nd Column
# arr2D = np.array(arr)
# sortedArr = arr2D[arr2D[:,columnIndex].argsort()]
# print('Sorted 2D Numpy Array')
# print(sortedArr)
result
[['0.55070000' '879.00000000']
['0.55350000' '879.00000000']
['0.55640000' '879.00000000']
['0.56210000' '879.00000000']
['0.56490000' '879.00000000']
['0.56780000' '879.00000000']
['0.57060000' '879.00000000']
['0.54500000' '899.00000000']
['0.56370000' '901.00000000']
['0.53070000' '908.00000000']
['0.57350000' '916.00000000']
['0.55000000' '9172.00000000']
['0.56300000' '939.00000000']
['0.54490000' '94.00000000']
['0.56040000' '96.00000000']
['0.54960000' '999.00000000']]
最后 4 和 5 行沒有顯示錯誤結果
uj5u.com熱心網友回復:
該sorted()函式不會改變它arr本身,它只是回傳一個排序串列,然后您必須將其分配給某個變數。所以這樣做:
from operator import itemgetter
import pprint
arr=[['0.55070000', '879.00000000'], ['0.55350000', '879.00000000'], ...]
sorted_arr = sorted(arr,key=lambda x:x[1])
pprint.pprint(sorted_arr)
uj5u.com熱心網友回復:
您正在使用字串對陣列進行排序。將它們轉換float為 lambda 函式,然后嘗試 -
注意:確保分配排序函式的輸出。
arr_sorted = sorted(arr, key=lambda x: float(x[1]))
arr_sorted
[['0.54490000', '94.00000000'],
['0.56040000', '96.00000000'],
['0.55070000', '879.00000000'],
['0.55350000', '879.00000000'],
['0.55640000', '879.00000000'],
['0.56210000', '879.00000000'],
['0.56490000', '879.00000000'],
['0.56780000', '879.00000000'],
['0.57060000', '879.00000000'],
['0.54500000', '899.00000000'],
['0.56370000', '901.00000000'],
['0.53070000', '908.00000000'],
['0.57350000', '916.00000000'],
['0.56300000', '939.00000000'],
['0.54960000', '999.00000000'],
['0.55000000', '9172.00000000']]
如果您希望按降序排序,請將reverse=True其sorted作為引數添加。
如果您想在排序后使用更多數值運算處理這個陣列,那么我建議首先將完整陣列轉換為浮點值,然后進行排序或其他操作。
arr2 = [[float(j) for j in i] for i in arr]
arr_sorted = sorted(arr2, key=lambda x: x[1])
arr_sorted
[[0.5449, 94.0],
[0.5604, 96.0],
[0.5507, 879.0],
[0.5535, 879.0],
[0.5564, 879.0],
[0.5621, 879.0],
[0.5649, 879.0],
[0.5678, 879.0],
[0.5706, 879.0],
[0.545, 899.0],
[0.5637, 901.0],
[0.5307, 908.0],
[0.5735, 916.0],
[0.563, 939.0],
[0.5496, 999.0],
[0.55, 9172.0]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/314584.html
上一篇:MongoDB按計算欄位排序
