在python中有一种简单的方法可以在给定范围内循环变量吗? 例如: 给定range(),我想要一个变量如下: 0 1 2 3 2 1 0 1 2 3 ...直到满足某些条件。
答案 0 :(得分: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
答案 1 :(得分:0)
您想要itertools.cycle()
,请参阅此处:
https://docs.python.org/2/library/itertools.html#itertools.cycle
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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"""
基本上,你只想循环并不断检查条件。并且每次从周期开始下一个项目。现在,诚然,有更好的方法来检查条件而不是函数调用,但这只是一个例子。
答案 5 :(得分: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