[英]python iterate over and select values from list of zipped arrays
我有几个多维数组已压缩到单个列表中,并且正在尝试根据应用于单个数组的选择条件从列表中删除值。 具体来说,我有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
压缩它们的顺序位于索引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)
将会抛出异常,因此请记住这一点并相应地调整代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.