I have 2 large array of integers A and B Now I have to sort A and B in the decreasing order of | A[i]-B[i]|
Example
A={16,5}
B={14,1}
|A[i]-B[i]|={2,4}
So sorted A={5,16}
sorted B={1,14}
The array can contain much more than 2 integers
I have 2 large array of integers A and B Now I have to sort A and B in the decreasing order of | A[i]-B[i]|
Example
A={16,5}
B={14,1}
|A[i]-B[i]|={2,4}
So sorted A={5,16}
sorted B={1,14}
The array can contain much more than 2 integers
Let's do it with 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]
If you prefer without NumPy (see 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]