首页 > 解决方案 > 将锯齿状列表转换为 numpy 数组

问题描述

我有由不同长度组成的列表(见下文)

[(880),
 (880, 1080),
 (880, 1080, 1080),
 (470, 470, 470, 1250)]

我想将它转换为相同的 numpy.array,即使我必须用零填充空格。

例如,它应该如下所示:

[(880, 0, 0, 0),
 (880, 1080, 0, 0),
 (880, 1080, 1080, 0),
 (470, 470, 470, 1250)]

怎么做?

标签: pythonarrayslistnumpy

解决方案


你可能会想,你的输入是一个元组列表。但是,它是整数和元组的列表。(880)将被解释为整数,而不是元组。所以你必须处理这两种数据类型。

首先,我建议将您的输入数据转换为列表列表。该列表中包含的每个列表都应具有相同的长度,因为数组仅支持常量维度。因此,我会将元素转换为列表并用零填充缺失值(以使所有元素的长度相等)。

如果我们对输入列表中给定的所有元素执行此操作,我们将创建一个新列表,其中包含可以转换为数组的等长列表。

一个非常基本(且容易出错)的方法如下所示:

import numpy as np


original_list = [
    (880),
    (880, 1080),
    (880, 1080, 1080),
    (470, 470, 470, 1250),
]


def get_len(item):
    try:
        return len(item)
    except TypeError:
        # `(880)` will be interpreted as an int instead of a tuple
        # so we need to handle tuples and integers
        # as integers do not support len(), a TypeError will be raised
        return 1


def to_list(item):
    try:
        return list(item)
    except TypeError:
        # `(880)` will be interpreted as an int instead of a tuple
        # so we need to handle tuples and integers
        # as integers do not support __iter__(), a TypeError will be raised
        return [item]


def fill_zeros(item, max_len):
    item_len = get_len(item)
    to_fill = [0] * (max_len - item_len)
    as_list = to_list(item) + to_fill
    return as_list


max_len = max([get_len(item) for item in original_list])
filled = [fill_zeros(item, max_len) for item in original_list]

arr = np.array(filled)
print(arr)

印刷:

[[ 880    0    0    0]
[ 880 1080    0    0]
[ 880 1080 1080    0]
[ 470  470  470 1250]]

推荐阅读