将数据放入特殊形状的列表中 [英] Put data in a particularly shaped list

查看:54
本文介绍了将数据放入特殊形状的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list that looks like this:

my_list = [[20, 15, 10], [15, 22, 37, 46], [22, 91]]

所以它是二维的,但并不是每行都具有相同数量的元素.

So it is two dimensional, but not every line has the same number of elements.

我现在有一个扁平的ndarray,例如:

I now have a flat ndarray, like:

my_ndarray = np.array([9, 2, 4, 4, 1, 6, 7, 8, 17])

具有与my_list相同数量的元素.现在,我想将my_ndarray的形状与my_list相同,即:

That have the same amount of elements with my_list. Now I would like to shape my_ndarray to be the same with my_list, i.e.:

my_ndarray = [[9, 2, 4], [4, 1, 6, 7], [8, 17]]

因此我们可以注意到,my_list和my_ndarray都包含3个子列表,第1个子列表包含3个元素,第2个子列表包含4个元素,第3个包含2个元素.

So we can note that, both my_list and my_ndarray contain 3 sublists, and 1st sublist contains 3 elements, 2nd sublists has 4, and 3rd has 2 elements in it.

有没有一种整齐的方法可以做到这一点?

Is there a neat way to do this?

谢谢!

推荐答案

>>> it = iter([9, 2, 4, 4, 1, 6, 7, 8, 17])
>>> my_list = [[20, 15, 10], [15, 22, 37, 46], [22, 91]]
>>> [[next(it) for i in j] for j in my_list]
[[9, 2, 4], [4, 1, 6, 7], [8, 17]]

这篇关于将数据放入特殊形状的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆