计算具有不同列表元素的新列表

时间:2019-04-16 12:26:51

标签: python numpy

我正在寻找一种更快的方法来计算两个列表的每个元素之间的绝对差。

这是我当前的代码,但是使用大数组会有点慢:

import numpy as np

np.random.seed(10)
x_values = np.random.randint(-50,100,size=(10))
test_values = x_values * 2
# print(x_values, test_values)
for x in test_values:
    test = sorted([(j, np.abs(j-x)) for j in x_values], key=lambda x: x[1])
    print(test)

输出:

[(-37, 37), (-17, 57), (4, 78), (12, 86), (27, 101), (38, 112), (50, 124), (57, 131), (72, 146), (76, 150)]
[(-37, 3), (-17, 17), (4, 38), (12, 46), (27, 61), (38, 72), (50, 84), (57, 91), (72, 106), (76, 110)]
[(12, 4), (4, 4), (27, 19), (-17, 25), (38, 30), (50, 42), (-37, 45), (57, 49), (72, 64), (76, 68)]
[(27, 3), (12, 12), (38, 14), (4, 20), (50, 26), (57, 33), (-17, 41), (72, 48), (76, 52), (-37, 61)]
[(57, 3), (50, 4), (38, 16), (72, 18), (76, 22), (27, 27), (12, 42), (4, 50), (-17, 71), (-37, 91)]
[(76, 0), (72, 4), (57, 19), (50, 26), (38, 38), (27, 49), (12, 64), (4, 72), (-17, 93), (-37, 113)]
[(76, 24), (72, 28), (57, 43), (50, 50), (38, 62), (27, 73), (12, 88), (4, 96), (-17, 117), (-37, 137)]
[(76, 38), (72, 42), (57, 57), (50, 64), (38, 76), (27, 87), (12, 102), (4, 110), (-17, 131), (-37, 151)]
[(76, 68), (72, 72), (57, 87), (50, 94), (38, 106), (27, 117), (12, 132), (4, 140), (-17, 161), (-37, 181)]
[(76, 76), (72, 80), (57, 95), (50, 102), (38, 114), (27, 125), (12, 140), (4, 148), (-17, 169), (-37, 189)]

1 个答案:

答案 0 :(得分:0)

这是一个纯粹的numpy解决方案。在速度方面,我没有将其与您的代码进行比较,所以请告诉我:

import numpy as np

np.random.seed(10)
x_values = np.random.randint(-50,100,size=(10))
test_values = x_values*2

# create a matrix of len(test_values) times the test_values column vector...
test_mat = np.array([test_values]*len(test_values)).T

# ... and then calculate the absolute difference matrix
abs_mat = np.abs(x_values - test_mat)

# this part is to obtain your desired output
output = np.column_stack((np.array([x_values]*len(x_values)).flatten(), abs_mat.flatten()))
output = np.split(output, len(x_values))