繁体   English   中英

如何将python字典转换为2D数组并在长度不匹配的地方填充?

[英]How to convert a python dictionary to an 2D array and pad wherever there is mismatch in length?

我正在尝试将字典项放入数组中。 键都是整数,但是每个值都是不同长度的列表。 我想转换为数组并填充零。 我有以下

a = {1:[0, 1], 2:[21], 3:[]}
lmax = 0
for item in a.values():
    lmax = len(item) if len(item) > lmax else lmax
t = np.zeros(len(a), lmax)
for key in a:
    t[ key, :len(a[key]) ] = a[key]

有没有更Python的方式来做到这一点?

谢谢

您似乎在代码中混用了键和值,所以我不确定该如何工作。

一种方法是

a = {1:[0, 1], 2:[21], 3:[]}
max_length = max(len(item) for item in a.values())
t = [[0] * (max_length - len(item)) + item for item in a.values()]

或者,如果您想确保列表按“正确”的顺序排列(即,原始字典中具有最低键的项首先显示),则可以将其更改为

t = [[0] * (max_length - len(item)) + item for _, item in sorted(a.items())]

对于lmax,

lmax = max(map(len, a.values()))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM