社区所有版块导航
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代码编写为java代码。在python中使用范围内的“for i:”[duplicate]将“i”递增“i/10”

Ramganga Chanani • 4 年前 • 1588 次点击  

在Python 2.7中,我想修改 for 循环中满足的特定条件的函数。比如:

step = 1
for i in range(1, 100, step):
    if ...... :
        step = 1
        #do stuff
    else:
        step = 2
        #do other stuff

但这似乎是做不到的, step 总是1。

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128737
文章 [ 6 ]  |  最新文章 4 年前
Acccumulation
Reply   •   1 楼
Acccumulation    9 年前

代码的第二行创建了一个范围对象,然后用于循环的其余部分,代码不会修改该范围对象。即使你改变了步长,也不会只改变范围的下一个元素,而是会改变整个范围对象(也就是说,将步长改为2会使 每一个 元素在范围内(比上一个元素多2个)。如果你真的想,你可以创建一个命名对象,并在for循环中修改它,但这将是一件相当麻烦的事情。

您还可以使用另一个与主循环不同的索引。例如:

actual_index = 1
for for_loop_index in range(1,100):
   if condition1:
        actual_index = actual_index + 1
   if condition2:
        actual_index = actual_index + 2
   if actual_index > 99:
        break

这基本上是一个while循环,除非对迭代次数有严格限制,这在某些用例中可能很有用。

sainoba
Reply   •   2 楼
sainoba    9 年前

您可以添加跳过检查:

skip = 0
for i in range(1, 100):
    if skip != 0:
        skip -= 1
        continue
    if ...... :
        #do stuff
    else:
        skip = 1
        #do other stuff
Jared Goguen
Reply   •   3 楼
Jared Goguen    9 年前

如果你想让事情变得过于复杂,你可以创建一个定制的生成器,在那里你可以使用 generator.send 方法在迭代过程中传递新的步骤。

def variable_step_generator(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start

    while start < stop:
        test_step = yield start

        if test_step is not None:
            step = test_step
            yield

        start += step

用法如下:

variable_step_range = variable_step_generator(1, 100)
for i in variable_step_range:
    print i
    if i == 10:
        variable_step_range.send(10)
    if i == 90:
        variable_step_range.send(1)

#  1,  2,  3,  4,  5,  6,  7,  8,  9, 
# 10, 20, 30, 40, 50, 60, 70, 80, 90, 
# 91, 92, 93, 94, 95, 96, 97, 98, 99

但这其实只是一个包装纸 while 循环其他答案的建议。

WholesomeGhost
Reply   •   4 楼
WholesomeGhost    9 年前

你可以通过一个while循环来实现:

step = 1
i = 1
while i < 100:
    if ...... :
        step = 1
        #do stuff
    else:
        step = 2
        #do other stuff
    i+=step
Alex Guteniev bieboebap
Reply   •   5 楼
Alex Guteniev bieboebap    6 年前
import numpy as np
for i in np.arange(start,stop,stepwidth):
    # your stuff
OLIVER.KOO
Reply   •   6 楼
OLIVER.KOO    9 年前

你需要增加 step 手动操作,可以使用 while 环 checkout difference between while and for loop .

for语句遍历集合或iterable对象或 发电机功能。

while语句只是循环,直到条件为False。

如果你使用 虽然 循环您的代码如下所示:

step = 1
i = 1
while i < 100:
    if ...... :
        step = 1
        #do stuff
    else:
        step = 2
        #do other stuff
    i = i + step