【问题标题】:How to find the length of numpy arrays stored in a nested list?如何查找存储在嵌套列表中的 numpy 数组的长度?
【发布时间】:2022-01-24 16:35:32
【问题描述】:

我有一个 numpy 数组的嵌套列表,想找出所有嵌套子列表的每个数组的长度。我尝试了this solution,但无法解决我的问题。我这里的列表有两个嵌套列表:

import numpy as np
big_list = [[np.array([[1., 2.], [0., 0.], [4., 4.]]),
             np.array([[0., 1.], [5., 6.]])],
            [np.array([[7., 7.]]),
             np.array([[5., 0.], [1., 7.]])]]

第一个嵌套列表有两个长度数组:32。第二个嵌套列表有两个长度为12 的数组。所以,我希望最终结果是一个 numpy 长度数组:

np.array([[3, 2], [1, 2]])

我尝试了以下 for 循环。它以某种方式起作用,但我正在寻找一种更有效的方法。

len_rough = np.array([])
for i in range (len(big_list)):
    for j in range (len(big_list[i])):
        len_each = len (big_list[i][j])
        len_rough = np.append(len_each, len_rough)
len_rough = len_rough[::-1]

【问题讨论】:

  • np.array([[len(x) for x in y] for y in big_list])
  • 亲爱的@MichaelSzczesny,感谢您的帮助。非常感谢。

标签: python arrays nested-lists


【解决方案1】:

您可以使用递归函数来确定包含数组的长度。这适用于任何级别的嵌套。

def nested_len(obj, *, target_cls=np.ndarray):
    return [len(x) if isinstance(x, target_cls) else nested_len(x) for x in obj]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2021-02-14
    • 2010-11-07
    • 2014-12-13
    • 2012-06-29
    相关资源
    最近更新 更多