希望在python中返回矩阵中全为零的行数

2024-04-25 21:40:34 发布

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

我想返回一个输出,它是元素中全部为零的行数。这是我的python代码,我无法确定bug在哪里。你知道吗

def find_bully_1(A):

    n = len(A)
    candidate = 0
    count = 0


    for i in range(n):
        for j in range(n):
            if A[i][j] == 0:
                count = count + 1
        if count == n:
            candidate = candidate + 1
    return candidate




x = [[1,1,1,1],
 [0,0,0,0],
 [0,0,0,0],
 [0,1,0,0]]


find_bully_1(x)

The output should be 2 but it keeps return 1. 

Tags: the代码in元素forlenreturnif
3条回答

到目前为止,您的代码对所看到的每一个0都进行计数,但它应该只是对当前行中的0进行计数。要解决这个问题,需要在进入for j in range(n):循环之前将count重置为零。你知道吗

然而,用这种方法计算所有的零行是低效的。更好的方法是将^{}函数与^{}all结合使用。例如:

def find_bully_1(a):
    return sum(not any(u) for u in a)

x = [
    [1,1,1,1],
    [0,0,0,0],
    [0,0,0,0],
    [0,1,0,0],
]

print(find_bully_1(x))

输出

2

FWIW,我不会费心把代码放到函数中,因为Python函数调用相对较慢,调用函数所需的代码并不比编写代码本身短多少:

print(sum(not any(u) for u in x))

在您的示例中,计数只会永远每0递增一次,并且永远不会重置

只需在for循环开始时重置计数

def find_bully_1(A):

n = len(A)
candidate = 0


for i in range(n):
    count = 0 
    for j in range(n):
        if A[i][j] == 0:
            count = count + 1
    if count == n:
        candidate = candidate + 1
return candidate




x = [[1,1,1,1],
     [0,0,0,0],
     [0,0,0,0],
     [0,1,0,0]]


print(find_bully_1(x))

您可以使用sum

x = [[1,1,1,1], [0,0,0,0], [0,0,0,0], [0,1,0,0]]
new_x = sum(all(not b for b in i) for i in x)

输出:

2

相关问题 更多 >