两个相同大小列表之间变量移动(数字)的稀疏矩阵

2024-09-28 19:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建两个一维数组或数字列表的索引之间的差异的稀疏矩阵。这两行给出了时间“a”和稍后时间“b”的位置。你知道吗

a = [6,3,10,2,5,7,4,11,8,9]
b = [10,3,6,5,11,2,7,8,9,4]

如您所见,“6”已从索引0移动到索引2。 从索引1到索引1的“3”。 从索引2到索引0的“10”。 “2”从索引3到索引5。 等等。。。你知道吗

我想把这个运动映射到一个稀疏的n*n矩阵上。 每一行和每一列从2开始按以下数字顺序排列:

>>>sorted(a)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

下面是我想要的最终结果(运动的稀疏矩阵)。你知道吗

array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
   [ 1.,  0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.]])

这是我绘制的图表的一个代表: graph of positions

其中第一列由列表a表示,第二列由列表b表示

粉色高光表示向指数0(向上)移动。 黄色荧光灯表示向下移动。 没有荧光灯意味着位置没有变化。你知道吗

这就是我所拥有的:

>>>import numpy as np
>>>sparse = np.zeros((len(a),len(a)))
>>>sparse.shape
(10, 10)
>>>a_unique = np.unique(np.array(b), return_index=True)
>>>b_unique = np.unique(np.array(b), return_index=True)
>>>a_unique
(array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11]), array([3, 1, 6, 4, 0, 5, 8, 9, 2, 7]))
>>>b_unique
(array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11]), array([5, 1, 9, 3, 2, 6, 7, 8, 0, 4]))

如果我们从一个唯一的中减去一个唯一的,这就得到了:

>>> a_unique[1]-b_unique[1]
array([-2,  0, -3,  1, -2, -1,  1,  1,  2,  3])

^在稀疏矩阵中,负数垂直表示为其他数字的位置(即数字从列表A向下移动到列表b,即黄色荧光笔)。你知道吗

^在稀疏矩阵中,正数水平表示为从其他数字接收到的位置(即,该数字已从列表A向上移动到列表b,即粉红色荧光笔)。你知道吗

我不知道如何继续解决这个问题,因此为什么我需要帮助。你知道吗


Tags: true列表indexlenreturnnp时间矩阵
1条回答
网友
1楼 · 发布于 2024-09-28 19:04:57

我睡了一觉就解决了这个问题。你知道吗

def seq_movement(a,b):
    import numpy as np
    def counter(items):
    counts = dict()
    for i in items:
        counts[i] = counts.get(i, 0) + 1
    return counts

    def find_2(dic):
        return [k for k, v in dic.items() if v ==2]

    sort = sorted(a)
    sparse = np.zeros([len(sort)]*2)

    while sorted(a) == sorted(b):
        for i,j in enumerate(sort):
                ai = a.index(j)
                bi = b.index(j)
                abovea = a[:ai]
                belowb = b[bi:]
                receiving = find_2(counter(belowb + abovea)) #row
                for row_ele in receiving:
                    sparse[i][sort.index(row_ele)] = 1
                belowa = a[ai:]
                aboveb = b[:bi]
                giving = find_2(counter(belowa + aboveb)) #column
                for col_ele in giving:
                    sparse[:,i][sort.index(col_ele)] = 1
         break     
    return sparse

它需要像示例中那样的a&b输入。 首先,我们要确保在列表a和b中有相同的参与者

我们遍历参与者列表,在列表a中找到参与者j下方的参与者,然后在列表b中找到参与者j上方的参与者

然后我们将这些列表连接在一起,并找出哪些参与者在合并列表中出现两次。两次出现的参与者是超过参与者j的参与者,因此稀疏矩阵中的j列将有1个位置来表示这一点。你知道吗

然后对参与者j以上的参与者执行此过程,随后j将从该参与者接收1(即行数字)。你知道吗

任何其他问题请随时询问!你知道吗

任务完成了。你知道吗

相关问题 更多 >