相关疑难解决方法(0)

python any()函数究竟是如何工作的?

在python docs页面中any,any()函数的等效代码如下:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
Run Code Online (Sandbox Code Playgroud)

如果以这种形式调用它,这个函数如何知道我想测试哪个元素?

any(x > 0 for x in list)
Run Code Online (Sandbox Code Playgroud)

从函数定义中,我只能看到我传递的是一个可迭代对象.for循环如何知道我正在寻找什么> 0

python

97
推荐指数
5
解决办法
14万
查看次数

检查NumPy数组是否包含另一个数组

使用NumPy和Python 2.7,我想创建一个n-by-2数组y.然后,我想检查此数组是否z在其任何行中包含特定的1 x 2数组.

这是我到目前为止所尝试的,在这种情况下,n = 1:

x = np.array([1, 2]) # Create a 1-by-2 array
y = [x] # Create an n-by-2 array (n = 1), and assign the first row to x
z = np.array([1, 2]) # Create another 1-by-2 array
if z in y: # Check if y contains the row z
    print 'yes it is'
Run Code Online (Sandbox Code Playgroud)

但是,这给了我以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() …
Run Code Online (Sandbox Code Playgroud)

python numpy

4
推荐指数
2
解决办法
6807
查看次数

如何检查 numpy 数组列表是否包含给定的测试数组?

我有一个numpy数组列表,比如说,

a = [np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)]
Run Code Online (Sandbox Code Playgroud)

我有一个测试数组,比如说

b = np.random.rand(3, 3)
Run Code Online (Sandbox Code Playgroud)

我想检查是否a包含b。然而

b in a 
Run Code Online (Sandbox Code Playgroud)

引发以下错误:

ValueError:包含多个元素的数组的真值不明确。使用 a.any() 或 a.all()

我想要的正确方法是什么?

python numpy

4
推荐指数
1
解决办法
2896
查看次数

Numpy:如何检查 ndarray 中元组的存在

在处理 numpy 数组中的元组时,我发现了一个奇怪的行为。我想得到一个布尔值表,告诉我数组中的哪些元组a也存在于数组中b。通常情况下,我会用任何的inin1d。它们都不起作用而tuple(a[1]) == b[1,1]yield True

我填写我的ab喜欢这样的:

a = numpy.array([(0,0)(1,1)(2,2)], dtype=tuple)

b = numpy.zeros((3,3), dtype=tuple)
for i in range(0,3):
    for j in range(0,3):
        b[i,j] = (i,j)
Run Code Online (Sandbox Code Playgroud)

谁能告诉我解决我的问题的方法,请告诉我为什么这不能按预期工作?

(顺便说一句,在这里使用 python2.7 和 numpy1.6.2。)

python comparison numpy

2
推荐指数
1
解决办法
2910
查看次数

如何检查 Numpy 数组的每一行是否包含在辅助数组中?

我的问题类似于测试 Numpy 数组是否包含给定的行,但我需要对链接问题中提供的方法进行非平凡的扩展;链接的问题是询问如何检查数组中的每一行是否与另一行相同。这个问题的重点是对许多行这样做,其中一个显然不会跟随另一个。

说我有一个数组:

array = np.array([[1, 2, 4], [3, 5, 1], [5, 5, 1], [1, 2, 1]])
Run Code Online (Sandbox Code Playgroud)

我想知道这个数组的每一行是否在由以下给出的辅助数组中:

check_array = np.array([[1, 2, 4], [1, 2, 1]])
Run Code Online (Sandbox Code Playgroud)

理想情况下,这看起来像这样:

is_in_check = array in check_array
Run Code Online (Sandbox Code Playgroud)

其中 is_in_check 看起来像这样:

is_in_check = np.array([True, False, False, True])
Run Code Online (Sandbox Code Playgroud)

我意识到对于非常小的数组,使用列表理解或类似的东西会更容易,但是该过程必须对 10 6行的数组具有高性能。

我已经看到检查单行的正确方法是:

is_in_check_single = any((array[:]==[1, 2, 1]).all(1))
Run Code Online (Sandbox Code Playgroud)

但理想情况下,我想将其概括为多行,以便对过程进行矢量化。

在实践中,我希望看到每个数组的以下维度:

array.shape = (1000000, 3)
check_array.shape = (5, 3)
Run Code Online (Sandbox Code Playgroud)

python arrays numpy vectorization

2
推荐指数
1
解决办法
81
查看次数

标签 统计

python ×5

numpy ×4

arrays ×1

comparison ×1

vectorization ×1