简体   繁体   English

如何从Python中的邻接列表中选择子矩阵?

[英]How to select a submatrix from an adjacency list in Python?

I have an adjacency list where each array represents non-zero columns at that row (eg 0th array in the adj. list below means columns 2 and 6 are 1, and everything else is 0). 我有一个邻接列表,其中每个数组代表该行的非零列(例如,下面的adj。列表中的第0个数组意味着列2和6是1,其他一切都是0)。

adj_list = [[2, 6], [1, 3, 24], [2, 4], [3, 5, 21], [4, 6, 10], [1, 5, 7], [6, 8, 9], [7], [7, 10, 14], [5, 9, 11], [10, 12, 18], [11, 13], [12, 14, 15], [9, 13], [13, 16, 17], [15], [15], [11, 19, 20], [18], [18], [4, 22, 23], [21], [21], [2, 25, 26], [24], [24]] adj_list = [[2,6],[1,3,24],[2,4],[3,5,21],[4,6,10],[1,5,7],[6, 8,9],[7],[7,10,14],[5,9,11],[10,12,18],[11,13],[12,14,15],[9, 13],[13,16,17],[15],[15],[11,19,20],[18],[18],[4,22,23],[21],[21] ,[2,25,26],[24],[24]]

Given this adj. 鉴于此调整。 list, I would like to select a submatrix which has identical row and column indices that is given by: list,我想选择一个子矩阵,它具有相同的行和列索引,由下式给出:

submatrix = (0, 1, 2, 5, 22)

Each element in submatrix indicates a row number. 子矩阵中的每个元素表示行号。

1) For each row i in submatrix, I need to get ith array from adj_list (which is equivalent to getting ith row from an adjacency matrix) 1)对于每行i在子矩阵,我需要得到ith从阵列adj_list (其等同于获得ith行从邻接矩阵)

2) Then from that array, I need to extract the items that match with submatrix 2)然后从该数组中,我需要提取与子矩阵匹配的项目

For example, if I am currently looking at 3rd element in submatrix , which is 5, then I need to go to 5th array in adj_list (equivalent of getting 5th row of adj.matrix), which is [1,5,7], and then I need to look which elements in [1,5,7] matches with submatrix (equivalent of getting 1th, 5th and 7th columns of the 5th row). 例如,如果我正在查看submatrix中的第3个元素,即5,那么我需要转到adj_list中的第5个数组(相当于获得第5行adj.matrix),这是[1,5,7],然后我需要查看[1,5,7]中哪些元素与子矩阵匹配(相当于获得第5行的第1,第5和第7列)。 In this case, the result for 5th row should be [0,1,0,1,0] because only 1 and 5 are intersected in two arrays). 在这种情况下,第5行的结果应为[0,1,0,1,0],因为在两个数组中只有1和5相交。

How can I efficiently select this submatrix given the adj. 如何在给定adj的情况下有效地选择该子矩阵。 list? 清单?

adj_list = [[2, 6], [1, 3, 24], [2, 4], [3, 5, 21], [4, 6, 10], [1, 5, 7], [6, 8, 9], [7], [7, 10, 14], [5, 9, 11], [10, 12, 18], [11, 13], [12, 14, 15], [9, 13], [13, 16, 17], [15], [15], [11, 19, 20], [18], [18], [4, 22, 23], [21], [21], [2, 25, 26], [24], [24]]

submatrix = (0, 1, 2, 5, 22)

result = [[i in adj_list[sm] for i in submatrix] for sm in submatrix]

This should do it; 这应该做到; though I suspect you might prefer to compute something other than this if you consider your end goal more carefully. 虽然我怀疑如果你更仔细地考虑你的最终目标,你可能更愿意计算除此之外的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM