在Python中按两列之间的差异绝对值排序

时间:2015-01-21 06:47:32

标签: python python-2.7 sorting greedy

我有2个大整数A和B数组 现在我必须按|的降序排序A和B. A [1] -B [I] |

Example
A={16,5}
B={14,1}
|A[i]-B[i]|={2,4}
So sorted A={5,16}
   sorted B={1,14}

数组可以包含多于2个整数

1 个答案:

答案 0 :(得分:0)

让我们用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]