python给指定范围内循环变量方法是?,python变量,Hi,在python中有
python给指定范围内循环变量方法是?,python变量,Hi,在python中有
Hi,在python中有简单的写法可以让我在给定范围内往复循环一个变量吗?
如,给定range(4),我希望变量像这样变化:
0,1,2,3,2,1,0,1,2,3....直到变化指定的次数或者其它条件满足为止。
只是整数的话,直接取余就行
pythonimport itertoolsdef bounce(interval): """Infinite bounce for specific range list.""" down = reversed(interval[1:-1]) return itertools.cycle(itertools.chain(interval, down))# >>> list(itertools.islice(bounce(range(5)), 20))# [0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3]
itertools.cycle(iterable)
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 cycle(iterable): # cycle('ABCD') --> A B C D A B C D A B C D ... saved = [] for element in iterable: yield element saved.append(element) 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 = chain(range(n), range(n - 2, 0, -1))for i in cycle(base_sequence): # do something if condition_satisfied: break
编橙之家文章,
相关内容
- Python flask只能return吗,pythonflaskreturn,from flask i
- Python猜数字游戏结果第一次不输出问题,python猜数字
- 关于设置WTForms初始化默认值的一个问题,wtforms初始化
- Python from tutorial.items import DmozItem报错问题,,items.py文件
- 多行python print信息中,怎么能目标是哪个print输出的呢
- 求问嵌套问题,列表里边可以放字典类型的数据吗?,
- python如何才能实时获取tcpdump的输出,pythontcpdump,linux
- Python新手flask遇到500错误问题,python新手flask500,为什么
- Django做后台管理操作疑问,django后台管理,服务器使用的
- 想用python做个客户端,在二维码登录这个地方卡住了大家
评论关闭