-2

Is there a clean pythonic (Python 3.6) way to achieve

(arr[0] > 1) & (arr[1] > 1) & (arr[2] > 1) & ... & (arr[N - 1] > 1)

for any array arr with arr.shape = (N, M)?

rtime
  • 349
  • 6
  • 23
  • 2
    1. Provide an example for `arr`. 2. At the end of your checks, you have `arr[N] > 0`, is that supposed to be `arr[N] > 1`? – aneroid Apr 19 '21 at 09:58
  • Yes, it is supposed to be arr[N] > 1 and I fixed it now. Sorry for the typo. Regarding an example, it should not matter how 'arr' looks like. You can take arr = np.random.rand(N, M) – rtime Apr 19 '21 at 10:01
  • You aren't trying to create a list, so why would this be a list comprehension? Also to be clear, is this a numpy array you're talking about? – kaya3 Apr 19 '21 at 10:01
  • 1
    Is `arr` a numpy array or a standard Python list of lists? Hence I said, provide an example for `arr`. – aneroid Apr 19 '21 at 10:03
  • 2
    Isn't `arr[N]` out of bounds? – kaya3 Apr 19 '21 at 10:04
  • Since you've referred to `arr.shape`, you're _probably_ using a numpy array. In whcih case, [Use a.any() or a.all()](https://stackoverflow.com/questions/34472814/use-a-any-or-a-all) – aneroid Apr 19 '21 at 10:08
  • Perhaps something like `np.all(arr > 1, axis=0)`? (assuming arr is a numpy array). – Heike Apr 19 '21 at 10:08

1 Answers1

1

For an array with only 1 row, you can do something like:

arr = [1, 2, 4, 5]
import functools
functools.reduce(lambda a, b: a & b, [(arr[x] > 1) for x in range(0, len(arr))])

However, an explicit for loop, instead of using reduce, might be better for readability.

For an array with more than 1 row, the concept remain the same:

arr = [[1, 2, 4, 5], [231, 542]]
import functools
functools.reduce(lambda a, b: a & b, [(arr[x][y] > 1) for x in range(0, len(arr)) for y in range(0, len(arr[x]))])
lolloz98
  • 111
  • 5