python循环嵌套的内循环控制变量_Python中用于循环的多个循环控制变量

I came across a situation where I need to implement a for loop with more than one loop control variable. Basically this is what I am trying to do

Java:

for (int i=0,j=n; i=0; i++, j--)

do my stuff

How do I do this in Python?

for i in range(0,n), j in range(n-1,-1,-1):

do my stuff

But this doesn't work. What would be the right syntax here? Also, is there a more elegant(pythonic) construct for the use-case?

解决方案

For your specific example, it doesn't look like you really need separate variables in the loop definition itself. You can just iterate over the i values and construct the j values by doing n-i:

for i in range(0, n):

j = n-i

# do stuff

In general, you can't specify multiple values in the for statement if they depend on each other. Instead, use the for to iterate over some "base" value or values from which the others can be derived.

You can specify multiple values in the for loop, but they must be drawn from a single iterable:

for i, j in zip(range(0, n), range(n, 0, -1)):

# do stuff

This takes i from the first range (0 to n-1) and j from the second (n to 1). zip creates a new iterable by componentwise pairing the elements of the iterables you give it.

The thing to remember is that Python for loops are not like loops in Java/C, which have an initialize/check end condition/update structure that repeatedly modifies some persistent loop index variable. Python for loops iterate over a "stream" of values provided by a "source" iterable, grabbing one value at a time from the source. (This is similar to foreach-type constructs in some other languages.) Whatever you want to iterate over, you need to get it into an iterable before you begin the loop. In other words, every Python for loop can be thought of as roughly analogous to something like:

for (i=iterable.getNextValue(); iterable.isNotEmpty(); i=iterable.getNextValue())

You can't have the loop initialization be different from the loop update, and you can't have those be any operation other than "get the next value", and you can't have the end condition be anything other than "is the iterable exhausted". If you want to do anything like that, you have to either do it yourself inside the loop (e.g., by assigning a secondary "loop variable" as in my example, or by checking for a custom loop exit condition and breaking out), or build it into the "source" that you're iterating over.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值