将可变大小的子列表的嵌套列表展平为 SciPy 数组 [英] Flatten a nested list of variable sized sublists into a SciPy array

查看:19
本文介绍了将可变大小的子列表的嵌套列表展平为 SciPy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用 numpy/scipy 来展平具有不同大小子列表的嵌套列表?速度很重要,列表很大.

How can I use numpy/scipy to flatten a nested list with sublists of different sizes? Speed is very important and the lists are large.

 lst = [[1, 2, 3, 4],[2, 3],[1, 2, 3, 4, 5],[4, 1, 2]]

还有比这更快的吗?

 vec = sp.array(list(*chain(lst)))

推荐答案

np怎么样.fromiter:

In [49]: %timeit np.hstack(lst*1000)
10 loops, best of 3: 25.2 ms per loop

In [50]: %timeit np.array(list(chain.from_iterable(lst*1000)))
1000 loops, best of 3: 1.81 ms per loop

In [52]: %timeit np.fromiter(chain.from_iterable(lst*1000), dtype='int')
1000 loops, best of 3: 1 ms per loop

这篇关于将可变大小的子列表的嵌套列表展平为 SciPy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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