简体   繁体   中英

Python: How to iterate an n-dimensional matrix?

I have a matrix with shape (1 , 255, 13, 13), so I have 13x13=169 elements and for each of this elements I have a array of 255 elements.

I want to iterate over the fourth element of the 255 array and count how many elements are greater than 0.5.

This code doesn't work but help to understand what I want:

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

What is the best way to do this?

if I understand you correctly:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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