Python迭代并从压缩数组列表中选择值



我有几个多维数组,它们被压缩到一个列表中,我试图根据应用于单个数组的选择标准从列表中删除值。具体来说,我有4个数组,它们都具有相同的形状,它们都被压缩到一个数组列表中:

    in: array1.shape
    out: (5,3)
    ...
    in: array4.shape
    out: (5,3)
    in: array1
    out: ([[0, 1, 1],
          [0, 0, 1],
          [0, 0, 1],
          [0, 1, 1],
          [0, 0, 0]])
    in: array4
    out: ([[20, 16, 20],
          [15, 19, 17],
          [21, 24, 23],
          [22, 22, 26],
          [27, 24, 23]])
    in: fullarray = zip(array1,...,array4)
    in: fullarray[0]
    out: (array([0, 1, 1]), array([3, 4, 5]), array([33, 34, 35]), array([20, 16, 20]))

我试图在每组数组内从单个目标数组迭代值,并在值等于20时选择与目标数组具有相同索引的每个数组的值。我想我没有解释清楚,所以我举个例子。

     in: fullarray[0]
     out: (array([0, 1, 1]), array([3, 4, 5]), array([33, 34, 35]), array([20, 16, 20]))
     what I want is to iterate over the values of the fourth array in the list for 
     fullarray[x] and where the value = 20 to take the value of each array with 
     the same index and append them into a new list as an array.
      so the output for fullarray[0] would be ([[0, 3, 33, 20]), [1, 5, 35, 20]]) 

我以前的尝试都产生了各种各样的错误消息(下面的例子)。如有任何帮助,不胜感激。

    in: for i in g:
          for n in i:
              if n == 3:
                 for k in n:
                     if k == 0:
                        newlist.append(i[k])
    out: for i in fullarray:
      2     for n in i:
----> 3         if n == 3:
      4             for k in n:
      5                 if k == 0:
     ValueError: The truth value of an array with more than one element is ambiguous. 
     Use a.any() or a.all()

编辑修改后的问题:

这段代码做了你想做的事。时间复杂度可能会得到改善。

from numpy import array
fullarray = [(array([0, 1, 1]), array([3, 4, 5]), array([33, 34, 35]), array([20, 16, 20]))]
newlist = []
for arrays in fullarray:
    for idx, value in enumerate(arrays[3]):
        if value == 20:
            newlist.append([array[idx] for array in arrays])
print newlist

旧答案:假设你所有的数组都是相同的大小,你可以这样做:full[idx]包含一个元组,其中包含索引idx处的所有数组的值,按您压缩它们的顺序。

import numpy as np
ar1 = np.array([1] * 8)
ar2 = np.array([2] * 8)
full = zip(ar1, ar2)
print full
newlist = []
for idx, v in enumerate(ar1):
    if v != 0:
        newlist.append(full[idx]) # Here you get a tuple such as (ar1[idx], ar2[idx]) 

但是if len(ar1) > len(ar2)会抛出异常,所以记住这一点并相应地调整你的代码

相关内容

  • 没有找到相关文章

最新更新