Python 将交错列表转换为numpy数组

Python 将交错列表转换为numpy数组,python,arrays,list,numpy,Python,Arrays,List,Numpy,我有不同长度的列表(见下文) 我想将其转换为外观相同的numpy.array,即使我必须用零填充空格 例如,它应该如下所示: [(880, 0, 0, 0), (880, 1080, 0, 0), (880, 1080, 1080, 0), (470, 470, 470, 1250)] import numpy as np original_list = [ (880), (880, 1080), (880, 1080, 1080), (470, 47

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

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

例如,它应该如下所示:

[(880, 0, 0, 0),
 (880, 1080, 0, 0),
 (880, 1080, 1080, 0),
 (470, 470, 470, 1250)]
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)将被解释为整数,而不是元组。因此,您必须处理这两种数据类型

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

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

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

[(880, 0, 0, 0),
 (880, 1080, 0, 0),
 (880, 1080, 1080, 0),
 (470, 470, 470, 1250)]
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]]