Python Chapter 7 Exercises plus(6)

Complete the function fun6, the parameter v is an n*m matrix with only 0 and 1, and find the number of 1

In this question, find out all the indexes that are 1, and then use the len function to know how many there are. After
doing this, you can also use the bincount function.

def fun6(v):
    '''
    Arg
    v:a 5*5 matrix ; return the total number of 1
    eg.[[0,1,1,0,1],
        [0,0,1,0,1],
        [0,1,1,0,0],
        [1,1,1,0,1],
        [1,0,1,0,1]]
    return 14
    '''
    v1=np.array(v)
    index=np.where(v1-1==0)
    return len(v1[index])

Guess you like

Origin blog.csdn.net/qq_53029299/article/details/115281838