【问题标题】:Getting python's itertools cycle current element获取python的itertools循环当前元素
【发布时间】:2016-07-03 06:21:24
【问题描述】:

我知道您可以使用c = cycle(['a', 'b', 'c']) 在使用c.next() 的元素之间循环,但是是否可以获取迭代器的当前元素?

例如如果c.next()返回'c',这意味着迭代器之前在'b'。有什么方法可以在不使用next() 的情况下获得'b'

【问题讨论】:

标签: python python-2.7


【解决方案1】:

迭代器/生成器无法获取当前值。您应该保留对它的引用或创建一些包装器来为您保留它。

【讨论】:

  • 这可以做到,即使不改变当前状态,见answer below
【解决方案2】:

注意:这仅适用于没有重复元素的情况。 这是否是一个严重的实际限制取决于每个人的使用。 就我而言,我合作过的大部分itertools.cycle 都属于这一类。

实际上可以通过辅助函数获取cycle 的当前状态,以及其他信息。 它实际上使用next,但这对调用者是透明的。

import itertools 

def get_cycle_props(cycle) :
    """Get the properties (elements, length, current state) of a cycle, without advancing it"""
    # Get the current state
    partial = []
    n = 0
    g = next(cycle)
    while ( g not in partial ) :
        partial.append(g)
        g = next(cycle)
        n += 1
    # Cycle until the "current" (now previous) state
    for i in range(n-1) :
        g = next(cycle)
    return (partial, n, partial[0])

def get_cycle_list(cycle) :
    """Get the elements of a cycle, without advancing it"""
    return get_cycle_props(cycle)[0]

def get_cycle_state(cycle) :
    """Get the current state of a cycle, without advancing it"""
    return get_cycle_props(cycle)[2]

def get_cycle_len(cycle) :
    """Get the length of a cycle, without advancing it"""
    return get_cycle_props(cycle)[1]

# initialize list 
test_list = [3, 4, 5, 7, 1] 
c = itertools.cycle(test_list)
print('cycle state =', get_cycle_state(c))
print('cycle length =', get_cycle_len(c))
print('cycle list =', get_cycle_list(c))
next(c)
print('cycle state =', get_cycle_state(c))
print('cycle length =', get_cycle_len(c))
print('cycle list =', get_cycle_list(c))

产生以下输出

cycle state = 3
cycle length = 5
cycle list = [3, 4, 5, 7, 1]
cycle state = 4
cycle length = 5
cycle list = [4, 5, 7, 1, 3]

这实际上可以利用函数来“倒回”一个循环

def shift_cycle(cycle, npos=0) :
    """Shift a cycle, a given number of positions (can be negative)."""
    (cycle_list, nelem, curr_state) = get_cycle_props(cycle)
    for i in range(nelem+npos) :
        g = next(cycle)
    return

试试

shift_cycle(c, -2)
print('cycle state =', get_cycle_state(c))

【讨论】:

  • 底部的“注释”应该更突出地突出显示,这是一个相当大的警告。对于像[1, 1, 2] 这样简单的事情,这将失败。
  • @cs95 - 已经强调...这是否是一个严重的实际限制取决于每个人的使用。就我而言,我使用过的大多数itertools.cycle 都属于这一类,所以它可以很好地工作。
猜你喜欢
  • 1970-01-01
  • 2021-05-23
  • 2013-03-01
  • 2019-10-01
  • 2013-09-10
  • 2017-10-12
  • 2012-08-04
  • 1970-01-01
  • 2013-02-15
相关资源
最近更新 更多