Python 使用其他列表中的值更改数组(条件)中的值

Python 使用其他列表中的值更改数组(条件)中的值,python,arrays,list,numpy,Python,Arrays,List,Numpy,我有以下清单: indices >>> [21, 43, 58, 64, 88, 104, 113, 115, 120] 我希望列表中出现的每一个值-1(比如20、42、57等)都从我拥有的3D数组“q”中调零 我尝试了列表理解,for和if循环(见下文),但总是出现以下错误: ValueError:包含多个元素的数组的真值为 模棱两可的使用a.any()或a.all() 我还没能解决这个问题 任何帮助都将是惊人的 >>> for b in q: ...

我有以下清单:

indices
>>> [21, 43, 58, 64, 88, 104, 113, 115, 120]
我希望列表中出现的每一个值-1(比如20、42、57等)都从我拥有的3D数组“q”中调零

我尝试了列表理解,for和if循环(见下文),但总是出现以下错误:

ValueError:包含多个元素的数组的真值为 模棱两可的使用a.any()或a.all()

我还没能解决这个问题

任何帮助都将是惊人的

>>> for b in q:
...     for u in indices:
...         if b==u:
...             b==0


>>> for u in indices:
...     q = [0 if x==u else x for x in q]

我试过这个,它对我有效:

>>> arr_2D = [3,4,5,6]
>>> arr_3D = [[3,4,5,6],[2,3,4,5],[4,5,6,7,8,8]]
>>> for el in arr_2D:
...    for x in arr_3D:
...       for y in x:
...          if y == el - 1:
...             x.remove(y)
... 
>>> arr_3D
[[6], [], [6, 7, 8, 8]]
在这种情况下,用列表理解来做可能会有点过头

或者将其归零,而不是删除

>>> for el in arr_2D:
...    for x in range(len(arr_3D)):
...       for y in range(len(arr_3D[x])):
...           if arr_3D[x][y] == el - 1:
...               arr_3D[x][y] = 0
... 
>>> arr_3D
[[0, 0, 0, 6], [0, 0, 0, 0], [0, 0, 6, 7, 8, 8]]
以下是清单:

zero_out = lambda arr_2D, arr_3D: [[0 if x in [el-1 for el in arr_2D] else x for x in y] for y in arr_3D]
这个怎么样

indices = range(1, 10)
>>[1, 2, 3, 4, 5, 6, 7, 8, 9]

q = np.arange(12).reshape(2,2,3)
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

def zeroed(row):
    new_indices = map(lambda x: x-1, indices)
    nrow = [0 if elem in new_indices else elem for elem in row]
    return now

np.apply_along_axis(zeroed, 1, q)

array([[[ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 0,  0,  0],
        [ 9, 10, 11]]])

我认为这是一种简单有效的方法:

b= b*np.logical_not(np.reshape(np.in1d(b,indices),b.shape))
对于np.in1d(),我们有一个布尔数组,其中b中的元素位于
索引中。我们将其重塑为as
b
,然后求反,这样我们就有了
False
(或者,如果你愿意,0),在这里我们想要归零
b
。把这个矩阵元素乘以b,就得到了


它的优点是适用于一维、二维、三维。。。数组

您希望删除它们还是将其归零?为什么不比较
x==u-1
?如果q是一个3D数组,那么你还需要一个嵌套的
用于
循环。你在使用numpy吗?是的,我在使用numpy。我想把索引中的每个值都归零。trincot,你能解释一下吗?太棒了:创新、简单、高效。你在运行什么版本的python?也许是你代码的另一部分导致了这个问题?你试过直接在解释器中运行它吗?Python 3.6.0;是的,所有的东西都直接进入翻译程序。托雷西拉的回答解决了这个问题,但仍然不确定为什么这样做行不通。但是,正如我所理解的,numpy导致了这个模糊问题,在这个例子中,我运行的是python2.7