【问题标题】:Flatten 3d list to 2d in python在python中将3d列表展平为2d
【发布时间】:2019-11-22 03:22:43
【问题描述】:

所以我在 python 中有一个类似这样的列表:

[[[0, 1, 0, 1, 0]]
[[1, 1, 1, 1, 1]]
[[1, 0, 0, 1, 1]]
[[0, 1, 0, 0, 0]]]

我想展平这个列表并最终得到这个:

[[0, 1, 0, 1, 0]
[1, 1, 1, 1, 1]
[1, 0, 0, 1, 1]
[0, 1, 0, 0, 0]]

在 python 中有没有直接的方法来做到这一点?

【问题讨论】:

  • 您能分享一个更易于复制/粘贴的列表版本吗?
  • 请加逗号
  • 好的,我用一个更简单的例子更改了列表。
  • 你需要list(chain.from_iterable(l))

标签: python list flatten


【解决方案1】:
a = [[[0, 1, 0, 1, 0]], 
[[1, 1, 1, 1, 1]], 
[[1, 0, 0, 1, 1]], 
[[0, 1, 0, 0, 0]]]    

[i[0] for i in a]     

输出

[[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [1, 0, 0, 1, 1], [0, 1, 0, 0, 0]]

【讨论】:

    【解决方案2】:

    使用numpy.squeeze 你可以做你想做的事:

    import numpy as np
    
    a = np.array([[[0, 1, 0, 1, 0]],
                  [[1, 1, 1, 1, 1]],
                  [[1, 0, 0, 1, 1]],
                  [[0, 1, 0, 0, 0]]])
    
    a.squeeze()
    
    [[0 1 0 1 0]
     [1 1 1 1 1]
     [1 0 0 1 1]
     [0 1 0 0 0]]
    

    【讨论】:

    • @yatu 我知道,list 已经有了答案,所以我将列表转换为np.array
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2019-09-12
    • 2020-10-15
    • 2014-07-11
    • 2012-04-25
    • 2017-10-08
    相关资源
    最近更新 更多