我已经将一些使用列表的代码更改为使用双队列。我不能再分析它了,因为我得到了错误:
TypeError:序列索引必须是整数,而不是'slice‘
这是一个显示问题的REPL。
>>> import collections
>>> d = collections.deque()
>>> for i in range(3):
... d.append(i)
...
>>> d
deque([0, 1, 2])
>>> d[2:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
那么,在Python中有没有一种变通方法来支持切分deques呢?
发布于 2012-04-04 08:04:47
试试itertools.islice()
。
deque_slice = collections.deque(itertools.islice(my_deque, 10, 20))
每次索引到deque
都需要从头开始遵循一个链表,因此islice()
方法,跳过项以到达切片的开头,将提供最佳的性能(比将其编码为每个元素的索引操作更好)。
您可以很容易地编写一个deque
子类,为您自动完成此操作。
class sliceable_deque(collections.deque):
def __getitem__(self, index):
if isinstance(index, slice):
return type(self)(itertools.islice(self, index.start,
index.stop, index.step))
return collections.deque.__getitem__(self, index)
请注意,您不能在islice
中使用负索引或步长值。可以围绕这一点进行编码,如果您采用子类方法,那么这样做可能是值得的。对于负的开始或停止,你可以只添加双队列的长度;对于负的步骤,你需要在那里的某个地方抛出一个reversed()
。我会把它留作练习。:-)
通过对切片进行if
测试,从deque
中检索单个项目的性能将略有下降。如果这是一个问题,您可以使用EAFP模式在一定程度上改进这一点--代价是由于需要处理异常而使切片路径的性能稍有下降:
class sliceable_deque(collections.deque):
def __getitem__(self, index):
try:
return collections.deque.__getitem__(self, index)
except TypeError:
return type(self)(itertools.islice(self, index.start,
index.stop, index.step))
当然,与常规的deque
相比,这里仍然有一个额外的函数调用,所以如果你真的关心性能,你真的想添加一个单独的slice()
方法或类似的方法。
https://stackoverflow.com/questions/10003143
复制相似问题