根据python中一个列表的值对两个嵌套列表排序



我想根据一个列表的值对两个嵌套列表进行排序。

predictions = np.array([[0, 1, 2, 3], [3, 2, 1, 0], [1, 2, 3, 0], [-1, -1, -1, -1]])
test_interaction_matrix = np.array([[1, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
for i,(p,t) in enumerate(zip(predictions, test_interaction_matrix)):
list1, list2 = (list(t) for t in zip(*sorted(zip(p, t))))
print(list1, list2)

排序标准取决于test_interaction_matrix的值,如果是1,则将预测中对应的元素放在前面。位置的变化应该发生在两个列表中。例如,我希望预测中的第一个列表看起来像[0,3,2,1],对应的列表在test_interaction_matrix中像[1,0,0,0],对于下一个[2,0,0,3,1]和[1,1,0,0]等等。现在打印列表,我没有得到正确的结果与我上面的代码。谢谢!

如果我正确理解了问题,下面应该可以工作:

import numpy as np
predictions = np.array([[0, 1, 2, 3], 
[3, 2, 1, 0], 
[1, 2, 3, 0],
[-1, -1, -1, -1]])
test_interaction_matrix = np.array([[1, 0, 0, 0], 
[0, 1, 0, 1], 
[0, 0, 0, 0],
[0, 0, 0, 0]])
r = predictions.shape[0]
sp = np.flip(predictions.argsort(axis=1), axis=1)
p = predictions[np.c_[:r], sp]
t = test_interaction_matrix[np.c_[:r], sp]
s = (-t).argsort(axis=1, kind="stable")
p = p[np.c_[:r], s]
t = t[np.c_[:r], s]
print(f"p:n{p}nnt:n{t}")

它给:

p:
[[ 0  3  2  1]
[ 2  0  3  1]
[ 3  2  1  0]
[-1 -1 -1 -1]]
t:
[[1 0 0 0]
[1 1 0 0]
[0 0 0 0]
[0 0 0 0]]

您可以使用列表推导来快速处理:

predictions = np.array([[0, 1, 2, 3], [3, 2, 1, 0], [1, 2, 3, 0], [-1, -1, -1, -1]])
test_interaction_matrix = [[1, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
pred = predictions.tolist()
order = test_interaction_matrix.tolist()
[list(zip(*sorted(zip(pred[i], order[i]), key=lambda pair: (pair[1], pair[0]), reverse=True)))[0] for i in range(len(pred))]

此代码循环遍历数组(for i in range(len(pred)))中的每个位置。

步骤1:对于每个位置,它将数组(zip(pred[i], order[i]))中的元素配对:

[[(0,1), (1,0), (2,0), (3,0)], [(3,0), (2,1), (1,0), (0,1)], [...], ...]

步骤2:对数组内的对进行排序(sorted(zip(...), key=lambda pair: (pair[1], pair[0]), reverse=True)):

key参数表明它将如何应用排序:它将优先考虑您的test_interaction_matrix值,然后是预测值。Reverse设置为True,这样您将获得降序。

[[(0,1), (3,0), (2,0), (1,0)], [(2,1), (0,1), (3,0), (1,0)], [...], ...]

步骤3:将重建原始向量test_interaction_matrix和predictions (list(zip(*sorted(...)))),简而言之就是第一步:

的逆操作。
[[(0, 3, 2, 1), (1, 0, 0, 0)], [(2, 0, 3, 1), (1, 1, 0, 0)], [...], ...]

步骤4:获取第一个数组(list(...)[0]),它对应于预测数组,这次排序为:

[(0, 3, 2, 1), (2, 0, 3, 1), (3, 2, 1, 0), (-1, -1, -1, -1)]

最新更新