注意:这仅适用于没有重复元素的情况。
这是否是一个严重的实际限制取决于每个人的使用。
就我而言,我合作过的大部分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))