python中有办法在给定范围内往复循环一个变量吗?

Hi,在python中有简单的写法可以让我在给定范围内往复循环一个变量吗?
如,给定range4,我希望变量像这样变化:
0,1,2,3,2,1,0,1,2,3….直到变化指定的次数或者其它条件满足为止。

pythonimport itertools def bounceinterval: """Infinite bounce for specific range list.""" down = reversedinterval[1:-1] return itertools.cycleitertools.chaininterval, down # >>> listitertools.islicebouncerange5, 20
# [0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3]

itertools.cycleiterable
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Equivalent to:

def cycleiterable: # cycleABCD --> A B C D A B C D A B C D ... saved = [] for element in iterable: yield element saved.appendelement while saved: for element in saved: yield element

Note, this member of the toolkit may require significant auxiliary storage depending on the length of the iterable.

只是整数的话,直接取余就行

其实我想要的是从小到大,再从大到下,再从小到大,并不是直接重复的过程。

我后来自己想了一个实现

from itertools import cycle, chain
# Get a sequence like 0,1,2,3,2,1
base_sequence = chainrangen, rangen - 2, 0, -1
for i in cyclebase_sequence: # do something if condition_satisfied: break

发表评论

电子邮件地址不会被公开。 必填项已用*标注