计算矩阵中行开头的零的问题

Problems counting zeroes standing at the beginning of rows in a matrix

在 Python 中,我尝试使用下面的代码来填充矩阵行中零出现的列表。这些 0 必须位于所有非零数字之前:例如在像 [0,0,3,0] 这样的行中,我只计算前两个零。

occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      while matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")

当我尝试使用先前定义的 dimmatrix 执行代码时,控制台从未吐出结果并冻结。为什么?

你可以使用 NumPy arr 它有 build-in 功能

In [3]: arr
Out[3]: 
array([[1, 2, 0, 3],
      [3, 9, 0, 4]])

In [4]: np.count_nonzero(arr==0)
Out[4]: 2

In [5]:def func_cnt():
            for arr in arrs:
                zero_els = np.count_nonzero(arr==0)
                # here, it counts the frequency of zeroes actually

问题是您没有退出 while 循环来递增 j。这是对您的代码的修复。

occurence_of_zeroes=[0]*dim
for i in range(dim):
    for j in range(dim):
        if matrix[i][j]!=0:
            break    
        occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
    print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")

您在那个 while 中进入了一个无限循环,因为在其中您没有根据它的条件更新任何变量

我假设你想要的是下面这样的东西。

matrix = [
    [0, 2, 3],
    [0, 0, 3],
    [0, 1, 0],
]
dim = 3 # 3 rows 3 columns I suppose
occurence_of_zeroes=[[] for _ in range(dim)]
for i in range(dim):
    j = 0
    while matrix[i][j]==0:
        occurence_of_zeroes[i].append(j)
        j+=1

print(occurence_of_zeroes)
"""
[
    [0], 
    [0, 1], 
    [0]
]
"""
while matrix[i][j]==0:
     occurence_of_zeroes[i]=occurence_of_zeroes[i]+1

是一个无限循环。只需使用 if 语句即可。

occurence_of_zeroes=[0]*dim
for i in range(dim):
   for j in range(dim):
      if matrix[i][j]==0:
         occurence_of_zeroes[i]=occurence_of_zeroes[i]+1
   print("In row ",i+1," there are ",occurence_of_zeroes[i]," zeroes at the beginning")
print("Is this working?")