如何为str,Python3的两个列表制作置换矩阵 [英] How to make permutation matrix for two lists of str, Python3

查看:144
本文介绍了如何为str,Python3的两个列表制作置换矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表.

a_num = [1, 3, 2, 4]
b_num = [1, 2, 3, 4]

我想找到一个将a转换为b的置换矩阵.在数学上,置换矩阵是一个方阵,其元素为1或0.它可以通过乘以向量来更改元素的顺序. 在此特定示例中,置换矩阵为:

I want to find a permutation matrix to convert a to b. Mathematically, a permutation matrix is a square matrix, whose elements are either 1 or 0. It can change the sequence of elements in a vector, by multiplying it. In this particular example, the permutation matrix is:

p = [[1,0,0,0],
     [0,0,1,0],
     [0,1,0,0],
     [0,0,0,1]]
# check whether p is correct.
b_num == np.dot(np.array(p), np.array(a_num).reshape(4,1))

能否请您告诉我如何制作该矩阵p?在我的实际应用中,列表中可以有数十个具有任意顺序的元素.并且两个列表始终包含str而不是int. 以及当abstr的列表时如何制作p?

Could you please show me how to make that matrix p? In my real application, there can be tens of elements in the lists with arbitrary sequence. And the two lists always contain str instead of int. And how to make p when the a and b are lists of str?

a_str = ['c1', 'c2', 's1', 's2']
b_str = ['c1', 's1', 'c2', 's2']

推荐答案

在纯Python中,您可以执行以下操作:

In pure Python you can do:

a_str = ['c1', 'c2', 's1', 's2']
b_str = ['c1', 's1', 'c2', 's2']

from collections import defaultdict

dd = defaultdict(lambda: [0, []])
for i, x in enumerate(b_str):  # collect indexes of target chars
    dd[x][1].append(i)

matrix = [[0]*len(a_str) for x in b_str]

for i, a in enumerate(a_str):
    # set cell at row (src index) and col (next tgt index) to 1
    matrix[i][dd[a][1][dd[a][0]]] = 1  
    # increment index for looking up next tgt index
    dd[a][0] += 1

matrix
# [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]

这假定a_strb_str实际上是各自的排列.

This assumes that a_str and b_str are in fact respective permutations.

这篇关于如何为str,Python3的两个列表制作置换矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆