【问题标题】:itertools 'previous' (opposite of next) pythonitertools'previous'(与下一个相反)python
【发布时间】:2017-06-18 05:04:46
【问题描述】:

我目前正在使用类似的东西

>> import itertools
>> ABC = [a, b, c]
>> abc = itertools.cycle( ABC )
>> next( abc )
a
>> next( abc )
b    
>> next( abc )
c

我希望我的下一个电话是

>> previous( abc )
b

itertools 中是否有方法可以做到这一点?

【问题讨论】:

标签: python python-3.x itertools


【解决方案1】:

不,没有。

由于 Python 的迭代协议的工作方式,如果不保留生成值的整个历史记录,就不可能实现 previous。 Python 不这样做,考虑到内存要求,您可能不希望它这样做。

【讨论】:

  • 谢谢!我想这就是我在文档中找不到它的原因。
【解决方案2】:

您可以使用来自collections 模块的dequerotate 方法, 例如:

from collections import deque

alist=['a','b','c']
d=deque(alist)

current = d[0] 
print(current) # 'a'

d.rotate(1) # rotate one step to the right
current = d[0] 
print(current) # 'c'

d.rotate(-1) # rotate one step to the left
current = d[0] 
print(current) # 'a' again

【讨论】:

    【解决方案3】:

    您可以编写自己的类来模拟带有下一个和上一个的iterable 对象。这是最简单的实现:

    class cycle:
        def __init__(self, c):
            self._c = c
            self._index = -1
    
        def __next__(self):
            self._index += 1
            if self._index>=len(self._c):
                self._index = 0
            return self._c[self._index]
    
        def previous(self):
            self._index -= 1
            if self._index < 0:
                self._index = len(self._c)-1
            return self._c[self._index]
    
    ABC = ['a', 'b', 'c']
    abc = cycle(ABC)
    print(next(abc))
    print(next(abc))
    print(next(abc))
    print(abc.previous())
    

    【讨论】:

    • 这不适用于任意可迭代对象(例如范围或由 itertools 生成的任何可迭代对象)。它只适用于可索引的对象。
    • 当然不是!但是这个例子是可索引的,所以这段代码可以工作。
    【解决方案4】:

    虽然deque 是要走的路,但这里有另一个例子:

    代码

    import itertools as it
    
    
    class Cycle:
        """Wrap cycle."""
        def __init__(self, seq):
            self._container = it.cycle(seq)
            self._here = None
            self.prev = None
    
        def __iter__(self):
            return self._container
    
        def __next__(self):
            self.prev = self._here
            self._here = next(self._container)
            return self._here
    

    演示

    c = Cycle("abc")
    next(c)
    # 'a'
    next(c)
    # 'b'
    c.prev
    # 'a'
    

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 2011-05-18
      • 2011-07-07
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2018-01-04
      相关资源
      最近更新 更多