简体   繁体   English

同时迭代多个numpy数组

[英]Iterating through multiple numpy arrays simultaneously

I have a numpy array with shape (n,), for example:我有一个形状为 (n,) 的 numpy 数组,例如:

[
    [0, 1],         # A
    [0, 1, 2, 3],   # B
    [0, 1, 2]       # C
]

How can I iterate through all 'tuples' formed by this array, in this case I would expect the return to be (0,0,0),(1,0,0),(0,1,0),(0,2,0),(0,3,0),(1,1,0)... and so on如何遍历由该数组形成的所有“元组”,在这种情况下,我希望返回为(0,0,0),(1,0,0),(0,1,0),(0,2,0),(0,3,0),(1,1,0)...等等

Here is a numpy solution for you.这是一个适合您的numpy解决方案。

inp = [
    [0, 1,],        
    [0, 1, 2, 3],  
    [0, 1, 2]       
]

Now you can simply现在你可以简单地

import numpy as np

shp = []
for sub_list in inp:
    shp.append(len(sub_list))

arr = np.ones(shp)

result = np.where(arr)

tuples = [t for t in zip(*result)]

out:出去:

 [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 3, 0), (0, 3, 1), (0, 3, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 3, 0), (1, 3, 1), (1, 3, 2)]

The way this works, is you build an array of ones whose dimensions are the lengths of your lists.它的工作方式是构建一个数组,其维度是列表的长度。
Then you get the multi dimensional indices of this array, which happen to be exactly what you wanted.然后你得到这个数组的多维索引,这恰好是你想要的。

If you also want to access your lists in the relevant index, you can easily do that as well.如果您还想访问相关索引中的列表,您也可以轻松实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM