gpt4 book ai didi

python - itertools.islice 实现——有效地切片列表

转载 作者:太空狗 更新时间:2023-10-29 17:49:24 24 4
gpt4 key购买 nike

早些时候,我试图回答一个问题,我想尽可能高效地遍历列表切片。

for x in lst[idx1:]:

并不理想,因为它会创建一个副本(通常,这是 O(n))。我的下一个想法是使用 itertools.islice .但是如果您查看文档,似乎 islice 会调用 next 直到它找到它正在寻找的索引,此时它将开始产生值。这也是 O(n)。如果传递给 islice 的对象是一个 list 或一个 tuple 似乎这里有一个可用的优化——看起来你可以直接迭代“切片”(在 C 中)而无需实际制作副本。我很好奇这个优化是否在 the source 中,但是我没有找到任何东西。我对 C 和 python 源代码树不是很熟悉,所以我完全有可能错过了它。

我的问题是:

Is there a way to iterate over a list "slice" without making a copy of the list slice and without burning through a bunch of unwanted elements (in an optimized C implementation)?

我很清楚我可以为此编写自己的生成器(非常天真,没有考虑到许多参数应该是可选的等事实):

def myslice(obj,start,stop,stride):
for i in xrange(start,stop,stride):
yield obj[i]

但这绝对不会击败优化的 C 实现。


如果你想知道为什么我需要这个而不是直接循环切片,请考虑以下之间的区别:

takewhile(lambda x: x == 5, lst[idx:])  #copy's the tail of the list unnecessarily

takewhile(lambda x: x == 5, islice(lst,idx,None)) #inspects the head of the list unnecessarily 

最后:

takewhile(lambda x: x == 5, magic_slice(lst,idx,None)) #How to create magic_slice???

最佳答案

我认为值得一提的是,NumPy 切片是不可复制的(它们创建底层数组的 View )。因此,如果您可以将 NumPy 数组用于您的数据,那将解决问题。最重要的是,您可以通过矢量化获得额外的性能改进。

关于python - itertools.islice 实现——有效地切片列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com