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

时间:2015-05-28 23:50:01

标签: python arrays numpy multidimensional-array iteration

我有几个多维数组已压缩到单个列表中,并且我尝试根据应用于单个数组的选择条件从列表中删除值。具体来说,我有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()

1 个答案:

答案 0 :(得分:0)

修改已修改的问题:

这是一段能够做你所喜欢的代码。但是时间复杂性可能会得到改善。

pause

旧回答:假设您的所有数组大小相同,您可以执行以下操作: 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]) 它会抛出异常,所以请记住并相应地调整代码。