栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python / NumPy第一次出现子数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python / NumPy第一次出现子数组

我假设您正在寻找特定于numpy的解决方案,而不是简单的列表理解或for循环。一种方法可能是使用滚动窗口技术来搜索适当大小的窗口。这是rolling_window函数:

>>> def rolling_window(a, size):...     shape = a.shape[:-1] + (a.shape[-1] - size + 1, size)...     strides = a.strides + (a. strides[-1],)...     return numpy.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)...

然后你可以做类似的事情

>>> a = numpy.arange(10)>>> numpy.random.shuffle(a)>>> aarray([7, 3, 6, 8, 4, 0, 9, 2, 1, 5])>>> rolling_window(a, 3) == [8, 4, 0]array([[False, False, False],       [False, False, False],       [False, False, False],       [ True,  True,  True],       [False, False, False],       [False, False, False],       [False, False, False],       [False, False, False]], dtype=bool)

为了使它真正有用,您必须使用沿轴1减小它

all

>>> numpy.all(rolling_window(a, 3) == [8, 4, 0], axis=1)array([False, False, False,  True, False, False, False, False], dtype=bool)

然后您可以使用它,但是您将使用布尔数组。一种获取索引的简单方法:

>>> bool_indices = numpy.all(rolling_window(a, 3) == [8, 4, 0], axis=1)>>> numpy.mgrid[0:len(bool_indices)][bool_indices]array([3])

对于列表,您可以调整这些滚动窗口迭代器之一以使用类似的方法。

对于 非常 大的数组和子数组,可以这样保存内存:

>>> windows = rolling_window(a, 3)>>> sub = [8, 4, 0]>>> hits = numpy.ones((len(a) - len(sub) + 1,), dtype=bool)>>> for i, x in enumerate(sub):...     hits &= numpy.in1d(windows[:,i], [x])... >>> hitsarray([False, False, False,  True, False, False, False, False], dtype=bool)>>> hits.nonzero()(array([3]),)

On the other hand, this will probably be slower. How much slower isn’t clear
without testing; see Jamie‘s
answer for another memory-conserving option that has to check false positives.
I imagine that the speed difference between these two solutions will depend
heavily on the nature of the input.




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645969.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号