在嵌套for循环中更改父for循环器的迭代器值?

时间:2017-05-21 14:02:28

标签: python loops

所以,我正在尝试使用Python解决竞争性编程,并遇到了需要使用嵌套循环的问题。我使用嵌套for循环并且如果在for循环中满足某些条件,则递增父for循环的迭代器的值。但是当子循环结束时,父循环的迭代器的值不会改变。

示例:

for i in range(5):
    print "When i = %d" % (i)
    for j in range(i+1,5):
        print j
        if j % 2 == 0:
            i = j

输出:

When i = 0
1
2
3
4
When i = 1
2
3
4
....

如何增加I的值并使循环运行次数减少,因为我想减少CPU时间和周期?

3 个答案:

答案 0 :(得分:2)

在python中

,如果你想更改valueiterator的{​​{1}},你应该使用loop。你的问题对你想要达到的目标不够清楚,但一个例子是:

while loop

答案 1 :(得分:1)

您的问题不够明确,但如果您想更改for循环,则应直接考虑使用while循环

答案 2 :(得分:0)

我在变量范围的断言中可能不正确,但无论如何,i循环遵循循环变量定义,与您尝试在循环中定义循环变量的方式无关。

以下是您的脚本发生了什么的示例。无论您如何设置range(5),它仍会经历整个In [1]: for i in range(5): print(i) i=10 print(i) Out [1]: 0 10 1 10 2 10 3 10 4 10

while

您需要for循环而不是i = 0 # initialize i while i<4: # ensure i stops at no more than 4 in the final iteration print "When i = %d" % i for j in range(i+1,5): print j if j % 2 == 0: i = j break # break out of the j loop if this condition is met else: # iterate i if none of the 'j %...' conditions are met ('break' is not encountered) i+=1 循环,因此您可以重新定义循环中的任何变量。如果我理解你的确切问题,我认为你正在寻找这个:

<div class="form-group">
    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
    </div>
</div>
相关问题