【问题标题】:Converting a list with numpy arrays into lists in Python将带有 numpy 数组的列表转换为 Python 中的列表
【发布时间】:2023-01-02 16:43:43
【问题描述】:

我有一个列表B11,其中包含一个 numpy 数组列表。我想将这些数组中的每一个都转换成列表,但出现错误。我还显示了预期的输出。

import numpy as np

B11=[[np.array([353.856161,   0.      ,   0.      ]), 
      np.array([  0.      ,   0.      , 282.754301,   0.      ])], 
     [np.array([  0.      , 294.983702, 126.991664])]]

C11=B11.tolist()

错误是

in <module>
    C11=B11.tolist()

AttributeError: 'list' object has no attribute 'tolist'

预期的输出是

[[[353.856161,   0.      ,   0.      ],[  0.      ,   0.      , 282.754301,   0.      ]],
 [  0.      , 294.983702, 126.991664]]

【问题讨论】:

    标签: python list numpy


    【解决方案1】:

    B11 已经是一个 python list - 它的元素是 numpy 数组。 您正在寻找类似 @​​987654323@ 的内容。

    这将遍历 B11 并创建一个新列表,其元素是通过对来自 B11 的每个子列表调用 .tolist() 方法构造的。

    【讨论】:

    • 我试过了,但出现错误:in &lt;listcomp&gt; C11 = [sublist.tolist() for sublist in B11] AttributeError: 'list' object has no attribute 'tolist'
    【解决方案2】:
    for x in B11:
        for y in x:
            print(y.tolist())
    
    #output:
    
    [353.856161, 0.0, 0.0]
    [0.0, 0.0, 282.754301, 0.0]
    [0.0, 294.983702, 126.991664]
    

    或列表理解以保留值:

    [[y.tolist() for y in x] for x in B11]
    
    #[[[353.856161, 0.0, 0.0], [0.0, 0.0, 282.754301, 0.0]],
    #[[0.0, 294.983702, 126.991664]]]
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2021-07-02
      • 2017-03-08
      • 2015-01-07
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多