Reputation: 443
I have an array with each index being another array. If I have an int, how can I write code to check whether the int is present within the first 2 indicies of each array element within the array in python.
eg: 3 in
array = [[1,2,3], [4,5,6]]
would produce False.
3 in
array = [[1,3,7], [4,5,6]]
would produce True.
Upvotes: 2
Views: 176
Reputation: 86276
You can use numpy.array
import numpy as np
a1 = np.array([[1,2,3], [4,5,6]])
a2 = np.array([[1,3,7], [4,5,6]])
You can do:
>>> a1[:, :2]
array([[1, 2],
[4, 5]])
>>> 3 in a1[:, :2]
False
>>> 3 in a2[:, :2]
True
Upvotes: 0
Reputation: 213311
You can slice your array to get a part of it, and then use in
operator and any()
function like this:
>>> array = [[1,2,3], [4,5,6]]
>>> [3 in elem[:2] for elem in array]
[False, False]
>>> any(3 in elem[:2] for elem in array)
False
>>> array = [[1,3,7], [4,5,6]]
>>> [3 in elem[:2] for elem in array]
[True, False]
>>> any(3 in elem[:2] for elem in array)
True
any()
function returns True
if at least one of the elements in the iterable is True
.
Upvotes: 5
Reputation: 12966
The first way that comes to mind is
len([x for x in array if 3 in x[:2]]) > 0
Upvotes: 0
Reputation: 213005
>>> a = [[1,2,3], [4,5,6]]
>>> print any(3 in b[:2] for b in a)
False
>>> a = [[1,3,7], [4,5,6]]
>>> print any(3 in b[:2] for b in a)
True
Upvotes: 3