社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中每x次迭代直到无穷大?

Hank • 5 年前 • 1697 次点击  

请考虑以下代码:

i = 0

while True:
    # Do some other stuff first.
    # Check if this iteration is after 7.
    i += 1
    if i % 7 == 0: print 'Factor of 7'

这个很好,但是柜台 i 迟早会是一个巨大的数字。有没有更好的方法来做一些长期的每x(在上面的例子中,每7次)迭代,这样我们就不必存储大量的数据了?我想到了以下几点:

i = 0

while True:
    # Do some other stuff first.
    # Check if this iteration is after 7.
    i += 1

    if i % 7 == 0:
        i = 0
        print 'Factor of 7'

但似乎有更好的办法。有什么建议吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41127
 
1697 次点击  
文章 [ 3 ]  |  最新文章 5 年前
LazyCoder
Reply   •   1 楼
LazyCoder    6 年前

怎么样:

i = 0
while True:
    # Do some other stuff first.
    i = (i+1)%7
    if i == 0:
        print 'Factor of 7'
Michael Butscher
Reply   •   2 楼
Michael Butscher    6 年前

你可以使用:

while True:
    for i in range(7):
        # Do some other stuff first.
    print 'Factor of 7'
Mark Meyer
Reply   •   3 楼
Mark Meyer    6 年前

你不需要一直增加 i 你只需要一遍又一遍地数到7。所以重新设置 当它击中你的计数时归零。那么你就不需要除法也不需要大量:

i = 0
while true:     
    # Do some other stuff first.
    # Check if this iteration is after 7.
    i += 1
    if i == 7:
        print('Factor of 7')
        i = 0 # reset