2015-01-14 50 views

回答

1

你想cycle序列0, 1, ..., n, n-1, ..., 1。 您可以輕鬆地構建利用chain

from itertools import chain, cycle 

def make_base_sequence(n): 
    base = range(n+1)     # 0, ..., n 
    rev_base = reversed(range(1, n)) # n-1, ..., 1 
    return chain(base, rev_base)  # 0, ..., n, n-1, ..., 1 

for x in cycle(make_base_sequence(5)): 
    print(x) 

樣品運行序列:

In [2]: from itertools import chain, cycle 
    ...: 
    ...: def make_base_sequence(n): 
    ...:  base = range(n+1) 
    ...:  rev_base = reversed(range(1, n)) 
    ...:  return chain(base, rev_base) 
    ...: 
    ...: for i, x in enumerate(cycle(make_base_sequence(5))): 
    ...:  print(x, end=' ') 
    ...:  if i > 20: 
    ...:   break 
    ...:  
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 
0

需要itertools.cycle

演示:

>>> import itertools 
>>> count = 0 
>>> for x in itertools.cycle(range(3)): 
...  if count == 10: 
...   break 
...  print x, 
...  count += 1 
... 
0 1 2 0 1 2 0 1 2 0 
+1

這是無效的代碼,你檢查「計數」,並分配給它,但你永遠不會初始化。 (另外,「count」是一個變量恕我直言的壞名字) –

0

itertools.cycle是一個良好的開端。否則,你可以自己編寫它:

cycle = [0,1,2,3,2,1] 
i = 0 
while some_condition: 
    value = cycle[i] 
    i = (i+1) % len(cycle) 
    #do stuff 
0
import itertools 

def f(cycle_range, condition_func): 
    sequence = range(cycle_range) + range(cycle_range)[-2:0:-1] 
    cycle_generator = itertools.cycle(sequence) 
    while not condition_func(): 
     yield next(cycle_generator) 

def condition_func(): 
    """Checks some condition""" 

從本質上講,你只是想循環並不斷檢查車況。並且每次都會從循環中提取下一個項目。現在,無可否認有更好的方法來檢查一個條件而不是函數調用,但這僅僅是一個例子。

0
import time 

def cycle(range_): 
    num = -1 
    current = 0 
    a=time.time() 
    while 1: 
     print current 
     if current in (0, range_): 
      num*=-1 
     current += num 
     if time.time() - a > 0.002: 
      break 

cycle(3) 

輸出:

0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2