简体   繁体   English

加速代码以过滤python中的矩阵

[英]Speeding up a code to filter a matrix in python

I have a symmetric matrix d1 of the from [[row1],[row2] etc] from which I want to remove some elements. 我有[[row1],[row2]等]的对称矩阵d1,我想从中删除一些元素。 The indices of the elements I want to remove are indicated in the list ind (eg ind = [1,2,3] means I want to remove d1[1][1],d1[2][2] and d1[3][3]). 我要删除的元素的索引在列表ind中指示(例如,ind = [1,2,3]表示我要删除d1 [1] [1],d1 [2] [2]和d1 [3 ] [3])。

I wrote the following piece of code to write the filtered matrix d1 in d2. 我编写了以下代码,将过滤后的矩阵d1写入d2。 However, it is taking forever to run. 但是,它需要永远运行。 Is there any way to speed up that code? 有什么办法可以加快代码的速度吗?

 for k in range(len(d1)):
     if k not in ind:
         d2.append([])
         for j in range(len(d1)):
             if j not in ind:
                 d2[-1].append(d1[k][j])

 print(d2)
 return d2

example: 例:

d1 = [[1, 2, 3,6,8],[4,5,6,6,6],[7,8,9,6,6],[1, 2, 3,6,6],[1, 2, 3,6,9]]

ind = [0,3]

d2 = [[5,6,6],[8,9,6],[2, 3,9]]

I would suggest to start with simple optimization: 我建议从简单的优化开始:

good_indices = set(range(len(d1))) - set(ind)

for k in good_indices:
    d2.append([])
    for j in good_indices:
        d2[-1].append(d1[k][j])

print(d2)
return d2

The main problem probably is that if ind is a very long list (thousands of entries) than each time you do if x not in ind you have to check the entire list . 主要问题可能是,如果ind是一个非常长的列表(成千上万个条目),则比每次if x not in ind时都要执行的列表都要长,您必须检查整个列表 Just changing ind to be a set will probably speed up things a lot. 仅将ind更改为set可能会大大加快速度。 Also, instead of checking the condition in both loops, you could just create a list of good indices to retain. 另外,您不必创建两个循环中的条件,而只需创建一个要保留的良好索引列表。 Finally, making it a list comprehension might speed it up still a bit more and make it more readable. 最后,使它成为列表理解器可能会使它的速度进一步提高并提高可读性。

ind_set = set(ind)
retain = [i for i in range(len(d1)) if i not in ind_set]
d2 = [[d1[k][j] for j in retain] for k in retain]

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

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