简体   繁体   English

当for循环的变量有一段时间时,如何才能进入for循环的步骤

[英]How can I get step jump in for loop when it has a while conditioned on the for loop's variable

My matrix is a 8x8 having binary values. 我的矩阵是一个具有二进制值的8x8。 I want to filter out patterns of consecutive three 1's ie(111) in the diagonals of upper triangular matrix of M. I have written a piece of python code with for and while loop but it did not work and I am unable to figure out whats happening there. 我想在M的上三角矩阵的对角线上滤除连续三个1的模式,即ie(111)。我用for和while循环编写了一段python代码,但没有用,我无法弄清楚是什么发生在那儿。 Please help.. 请帮忙..

rf =([1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0],
     [1,0,1,0,1,0,0,0])

for i in range(1):
    for j in range(len (rf)-3):
        while (i<len(rf)-3 and j<len(rf)-3):
             count =0
             if rf[i,j]==True:     
               for w in range(3):
                   if rf[i+w,j+w]==True:
                      count +=1
                      print count
               if count==3:
                  i=i+3
                  j=j+3
               else:
                    rf[i,j]=False
                    i=i+1
                    j=j+1

You might simplify your code using numpy to access diagonals: 您可以使用numpy来访问对角线,从而简化代码:

>>> import numpy as np
>>> rf = [[1,0,1,0,1,0,0,0]] * 8
>>> m = np.array(rf)
>>> m.diagonal(0)
array([1, 0, 1, 0, 1, 0, 0, 0])
>>> m.diagonal(1)
array([0, 1, 0, 1, 0, 0, 0])

a simply routine to find positions of consecutive ones: 查找连续位置的简单例程:

def consecutive_values(arr, val=1, cnt=3):
    def comparator(pos):
        return arr[pos] == val
    if len < cnt:
        return []
    else:
        return [p for p, x in  enumerate(arr[:1-cnt]) 
                     if all(map(comparator, xrange(p, p+cnt, 1)))]

and usage: 和用法:

>>> consecutive_values([1]*5)
[0, 1, 2]

>>> consecutive_values([1]*5 + [0]*4 + [1]*3)
[0, 1, 2, 9]

>>> m = np.array([[1]*8]*8)
>>> diagonals = map(m.diagonal, range(len(m)))
>>> map(consecutive_values, diagonals)
[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [0, 1, 2, 3], [0, 1, 2], [0, 1], [0], [], []]

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

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