[英]How to cycle a variable in a given range in python
python中有沒有一種簡單的方法可以在給定范圍內循環變量? 例如:給定一個range(),我想要一個變量如下:0 1 2 3 2 1 0 1 2 3 ...直到滿足某些條件。
您想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
您需要itertools.cycle()
,請參見此處:
https://docs.python.org/2/library/itertools.html#itertools.cycle
你需要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
itertools.cycle
是一個好的開始。 另外,您可以自己編程:
cycle = [0,1,2,3,2,1]
i = 0
while some_condition:
value = cycle[i]
i = (i+1) % len(cycle)
#do stuff
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"""
本質上,您只想循環並不斷檢查條件。 並且每次從循環中獲得下一個項目。 現在,誠然,有比函數調用更好的檢查條件的方法,但這只是一個例子。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.