Python:如何迭代n维矩阵?

时间:2019-05-20 00:07:50

标签: python for-loop

我有一个形状为(1、255、13、13)的矩阵,所以我有13x13 = 169个元素,对于每个元素,我有255个元素的数组。

我想遍历255数组的第四个元素,并计算有多少个元素大于0.5。

此代码不起作用,但有助于理解我想要的内容:

out = net.forward()

count1=0
count2=0

for i in out[0]:
    for j in out[2]:
        for a in out[3]:
            for b in out[1]:
                if b[3]> 0.5:

                    count1+=1
                else:
                    count2+=1

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的话:

def give_counts(out):
    """Count the fourth element of each cell if it is >0.5

    >>> x = [0, 0, 0, 3]  # should show up in counts1
    >>> o = [0, 0, 0, 0]  # should show up in counts2
    >>> out = [[x, o, o],
    ...        [x, x, x],
    ...        [o, o, x]]
    >>> counts1, counts2 = give_counts(out)
    >>> assert counts1 == 5
    >>> assert counts2 == 4
    """

    values = (True if col[3] > 0.5 else False for row in out for col in row)
    counts = collections.Counter(values)
    return counts[True], counts[False]