我有一个置换矩阵,它是一个方阵,元素为 1 或 0。
p = [[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]]
如果我将p
乘以一个int
列表,列表中元素的位置将会改变。例如
a_num = [1, 3, 2, 4]
np.dot(np.array(p), np.array(a_num).reshape(4,1))
# results is [1, 2, 3, 4]
现在我想更改 str
列表:
a_str = ['c1', 'c3', 'c2', 'c4']
至
['c1', 'c2', 'c3', 'c4']
你知道如何用矩阵p
实现它吗?请注意,我的实际应用程序列表中可能有数十个元素。
供您引用。有一个帖子是关于 How to generate permutation matrix based on two lists of str
最佳答案
您可以使用numpy.take
:
>>> numpy.take(numpy.array(a_str), numpy.array(a_num)-1)
array(['c1', 'c2', 'c3', 'c4'], dtype='|S2')
关于python - 如何更改列表中元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101905/