如何查找int是否在数组数组中?

时间:2021-05-26 07:37:01

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.

我有一个数组,每个索引是另一个数组。如果我有一个int,我怎么能编写代码来检查int是否存在于python中数组中每个数组元素的前2个指标内。

eg: 3 in

例如:3英寸

array = [[1,2,3], [4,5,6]] 

would produce False.

会产生假。

3 in

3英寸

array = [[1,3,7], [4,5,6]] 

would produce True.

会产生真的。

4 个解决方案

#1


5  

You can slice your array to get a part of it, and then use in operator and any() function like this:

您可以对数组进行切片以获取其中的一部分,然后在运算符和any()函数中使用,如下所示:

>>> 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.

如果iterable中至少有一个元素为True,则any()函数返回True。

#2


3  

>>> 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

#3


0  

The first way that comes to mind is

想到的第一种方式是

len([x for x in array if 3 in x[:2]]) > 0

#4


0  

You can use numpy.array

你可以使用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

#1


5  

You can slice your array to get a part of it, and then use in operator and any() function like this:

您可以对数组进行切片以获取其中的一部分,然后在运算符和any()函数中使用,如下所示:

>>> 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.

如果iterable中至少有一个元素为True,则any()函数返回True。

#2


3  

>>> 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

#3


0  

The first way that comes to mind is

想到的第一种方式是

len([x for x in array if 3 in x[:2]]) > 0

#4


0  

You can use numpy.array

你可以使用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