python - 将锯齿状列表转换为 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)]
怎么做?
解决方案
你可能会想,你的输入是一个元组列表。但是,它是整数和元组的列表。(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]]
推荐阅读
- sql - 如果左字段为空,则左连接并使用左字段,否则使用右字段
- curl - 为什么 curl 打印页面的 HTML 代码?
- java - 使用 Java Regex 将包含未知数量匹配项的字符串解析为 List
- javascript - 浏览器更新横幅按钮
- winforms - 在数组数组的末尾添加一个值
^ c++ winform - android - 如何将片段加载到我的 SlidingPaneLayout 菜单中?
- istio - Istio 0.8.0 需要 istio-proxy?
- loops - Loop、tab.Length 和无数个零
- enums - 图书馆作者选择子类型的首选替代方法是什么,为什么?
- php - 如何防止超链接出现在 gmail 消息中