从三维数组生成列表

时间:2014-06-13 00:20:42

标签: python arrays list recursion

我因阵列问题而苦苦挣扎一段时间。例如,如果我有以下三维数组:

import os
import numpy as np

myArray = [[[1,2,3],
            [0,0,0],
            [2,2,2]],
           [[0,1,2],
            [1,1,1],
            [3,3,3]],
           [[2,3,4],
            [5,6,7],
            [8,9,10]]]

我想以递归的方式为myArray [0]中的每个位置定义一个列表,该列表将值存储在Z轴上,以便:

list1 = [myArray[0][0][0],myArray[1][0][0], myArray[2][0][0]]  # would be [1,0,2]
list2 = [myArray[0][0][1],myArray[1][0][1], myArray[2][0][1]]  # would be [2,1,3]
list3 = [myArray[0][0][2],myArray[1][0][2], myArray[2][0][2]]  # would be [3,2,4]
list4 = [myArray[0][1][0],myArray[1][1][0], myArray[2][1][0]]  # would be [0,1,5]
list5 = [myArray[0][1][1],myArray[1][1][1], myArray[2][1][1]]  # would be [0,1,6]
list6 = [myArray[0][1][2],myArray[1][1][2], myArray[2][1][2]]  # would be [0,1,7]
list7 = [myArray[0][2][0],myArray[1][2][0], myArray[2][2][0]]  # would be [2,3,8]
list8 = [myArray[0][2][1],myArray[1][2][1], myArray[2][2][1]]  # would be [2,3,9]
list9 = [myArray[0][2][2],myArray[1][2][2], myArray[2][2][2]]  # would be [2,3,10]

我想它必须与

类似
for i in range(len(myArray[0])-1):
    list+str(i) =[something]

你知道如何生成这个吗?

非常感谢

2 个答案:

答案 0 :(得分:1)

因为你已经在使用numpy:

np.swapaxes(np.swapaxes(myArray,0,2),0,1)

输出:

array([[[ 1,  0,  2],
        [ 2,  1,  3],
        [ 3,  2,  4]],

       [[ 0,  1,  5],
        [ 0,  1,  6],
        [ 0,  1,  7]],

       [[ 2,  3,  8],
        [ 2,  3,  9],
        [ 2,  3, 10]]])

答案 1 :(得分:0)

我认为最明智的方法是使用numpy的数组切片和列表理解:

import numpy as np
from itertools import product

# use a numpy array
myArray = np.array([[[1,2,3],
                     [0,0,0],
                     [2,2,2]],
                   [[0,1,2],
                    [1,1,1],
                    [3,3,3]],
                   [[2,3,4],
                    [5,6,7],
                    [8,9,10]]])

# get the dimensions of the array
_, x, y = arr.shape

# slice along the appropriate axis
list1,list2,list3,list4,list5,list6,list7,list8,list9 = 
  [myArray[:,i,j] for i,j in product(xrange(x),xrange(y))]