Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all elements in a 2d array are equal to 1 in Python [duplicate]

Tags:

python

arrays

What's the most Python way to do this, other than iterating through nested loops and checking if each value is equal to 1?

like image 548
Milnik Avatar asked Dec 31 '25 18:12

Milnik


1 Answers

If you're using numpy you can use its per-element equality check and then call the resulting arrays all method to check if all elements did satisfy the condition:

>>> import numpy as np
>>> c = np.array([[1,2], [3,4]])
>>> (c==1).all()
False
>>> c = np.array([[1,1], [1,1]])
>>> (c==1).all()
True
like image 78
Moses Koledoye Avatar answered Jan 03 '26 07:01

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!