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

查看:50
本文介绍了将可变大小的子列表的嵌套列表展平到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天全站免登陆