What's the most Python way to do this, other than iterating through nested loops and checking if each value is equal to 1?
Asked
Active
Viewed 9,552 times
5 Answers
5
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

Moses Koledoye
- 77,341
- 8
- 133
- 139
2
Use itertoools.chain to iterate over "flattened" list
all(x == 1 for x in itertools.chain(*my_list))

volcano
- 3,578
- 21
- 28
1
Using sets:
from itertools import chain
array = [[1,1,1],[1,0,1]]
if set(chain.from_iterable(array)) == {1}:
print("all ones")

Daniel
- 42,087
- 4
- 55
- 81
-
1This is a neat alternative, but it might be worth noting that it will not allow short-circuiting in case of first non `1`-valued element found (as the `all` or `any` solutions will). – dfrib Oct 15 '16 at 10:43
0
Generator function + all
is probably the way to go.
array_2D = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
all(all(item == 1 for item in items) for items in array_2D)
Another option would be to first flatten the array, but python has no standard way to do this. But the code would handle any kind of dimensions (If you flatten it deep)!

TN1ck
- 691
- 4
- 10
-
1This will return `True` irregardless of the elements in the array. Check `array_2D = [[1, 1, 1], 'aadsd', [1, 1, 1]]` You're testing for the *truthiness* of genexps not values. You need to move that inner `for` behind the first one; more like list flattening – Moses Koledoye Oct 15 '16 at 10:46
-
-
-
@volcano A comprehension is an expression, so it returns something, which is useful for this, as we can use the result of the comprehension and feed it into `all`. A loop is a statement, so it doesn't return anything. In python it's idiomatic to use more comprehensions than loops for these kind of things. – TN1ck Oct 15 '16 at 12:35
-
0
You can use np.searchsorted along with np.apply_along_axis to find the elements in any dimensional array.

Arpan Das
- 321
- 1
- 3
- 9