如何在 Python 的循环中更改 for 循环迭代器变量? [英] How to change for-loop iterator variable in the loop in Python?

查看:101
本文介绍了如何在 Python 的循环中更改 for 循环迭代器变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 for 循环中更改迭代器的值?

I want to know if is it possible to change the value of the iterator in its for-loop?

例如,我想编写一个程序来计算一个数的素因数,如下所示:

For example I want to write a program to calculate prime factor of a number in the below way :

def primeFactors(number):
    for i in range(2,number+1):
        if (number%i==0)
            print(i,end=',')
            number=number/i 
            i=i-1 #to check that factor again!

我的问题:当我在 if 块中更改 inumber 时,是否可以更改最后两行,它们的值在 for 循环中发生变化!

My question : Is it possible to change the last two line in a way that when I change i and number in the if block, their value change in the for loop!

更新:将迭代器定义为 global 变量,可以帮助我吗?为什么?

Update: Defining the iterator as a global variable, could help me? Why?

推荐答案

简短回答(如 Daniel Roseman 的):否

Short answer (like Daniel Roseman's): No

长答案:不,但这可以满足您的需求:

Long answer: No, but this does what you want:

def redo_range(start, end):
    while start < end:
        start += 1
        redo = (yield start)
        if redo:
            start -= 2

redone_5 = False
r = redo_range(2, 10)
for i in r:
    print(i)
    if i == 5 and not redone_5:
        r.send(True)
        redone_5 = True

输出:

3
4
5
5
6
7
8
9
10

如您所见,5 被重复了.它使用了一个生成器函数,该函数允许重复索引变量的最后一个值.有更简单的方法(while 循环、要检查的值列表等),但这个方法与您的代码最接近.

As you can see, 5 gets repeated. It used a generator function which allows the last value of the index variable to be repeated. There are simpler methods (while loops, list of values to check, etc.) but this one matches you code the closest.

这篇关于如何在 Python 的循环中更改 for 循环迭代器变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆