【问题标题】:I'm trying to convert a 3D list from 2D list in Python 3我正在尝试从 Python 3 中的 2D 列表转换 3D 列表
【发布时间】:2019-06-14 11:21:03
【问题描述】:

我找不到任何适用于我要转换的列表类型的内容。二维列表是

[[2,3,4],[5,6,7],[8,9,10],[11,12,13]]

我需要一个像

这样的列表
[[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]

我已经尝试了所有这些,但它不起作用。我知道要转换的列表的大小。

a = np.array(item).reshape(3, round(len(item)/2),round(len(item)/2))
a = np.reshape(np.array(item), (round(len(item)/2), round(len(item)/2), 3))
a = np.array(item)[round(len(item)/2), round(len(item)/2), newaxis]

【问题讨论】:

  • a=np.array([a]) ?这是你想要的吗?
  • reshape((2,2,3))?
  • 第一个,作为数组,是 (4,3)。第二个看起来像(2,2,3)
  • 那么您的第二次尝试有什么问题?似乎完全符合您的要求...

标签: python arrays list numpy multidimensional-array


【解决方案1】:

首先将您的列表转换为数组并找出您想要的形状,然后相应地重新整形如何?

In [2]: lol = [[2,3,4],[5,6,7],[8,9,10],[11,12,13]] 
In [3]: lol_arr = np.array(lol)    

In [4]: lol3 = [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
In [5]: lol3_arr = np.array(lol3) 

In [6]: lol_arr.shape                  
Out[6]: (4, 3)

In [7]: lol3_arr.shape                             
Out[7]: (2, 2, 3)

# reshape accordingly
In [9]: np.reshape(lol_arr, (2, 2, 3))                                 
Out[9]: 
array([[[ 2,  3,  4],
        [ 5,  6,  7]],

       [[ 8,  9, 10],
        [11, 12, 13]]])

In [10]: np.reshape(lol_arr, (2, 2, 3)).tolist() 
Out[10]: [[[2, 3, 4], [5, 6, 7]], [[8, 9, 10], [11, 12, 13]]]

# or get the array shape directly
In [11]: np.reshape(lol_arr, lol3_arr.shape).tolist() 
Out[11]: [[[2, 3, 4], [5, 6, 7]], [[8, 9, 10], [11, 12, 13]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-15
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2021-06-04
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多