0
我有2個大整數A和B的大數組 現在我必須按照| A [1] -B [I] |按Python中兩列之差的絕對值排序
Example
A={16,5}
B={14,1}
|A[i]-B[i]|={2,4}
So sorted A={5,16}
sorted B={1,14}
陣列可以包含更多比2的整數
我有2個大整數A和B的大數組 現在我必須按照| A [1] -B [I] |按Python中兩列之差的絕對值排序
Example
A={16,5}
B={14,1}
|A[i]-B[i]|={2,4}
So sorted A={5,16}
sorted B={1,14}
陣列可以包含更多比2的整數
讓我們NumPy的做吧!
import numpy as np
A = np.random.randint(0, 100, 100) # or np.array(A) to convert from list
B = np.random.randint(0, 100, 100)
diff = np.abs(A-B) # your sort order
sortidx = np.argsort(diff) # indexes which sort the data by diff
print A[sortidx] # print A sorted in order of abs(A-B)
print B[sortidx]
如果你喜歡不NumPy的(見Equivalent of Numpy.argsort() in basic python?):
import operator
diff = map(operator.sub, A, B)
sortidx = sorted(range(len(diff)), key=diff.__getitem__)
print [A[idx] for idx in sortidx]
print [B[idx] for idx in sortidx]
先生,你能告訴我什麼是NumPy的?我是python的初學者 – user220789 2015-01-21 06:57:21
請嘗試Google。如果NumPy令人害怕,我也發佈了一個常規的Python解決方案。 – 2015-01-21 07:01:01