双循环的迭代计数器

时间:2017-04-27 14:32:09

标签: python algorithm nested-loops

我试图找到计算这个双for循环的每次迭代的公式(例如在python中):

for i in range(5):
   for j in range(5):
       count = MYSTERIOUS_FORMULA
       print count

这里count的最终值应为25。

我尝试了count=(i+1)*j,但它产生了0,1,2,3,4,0,2,4等。

4 个答案:

答案 0 :(得分:3)

Double-for-loop(a.k.a.嵌套循环)。

# Set count to 0 before loop starts
count = 0

for i in range(5):
    for j in range(5):
        # solved mysterious formula (short hand 'count = count + 1')
        count += 1
# displaying count after loop
print(count)

扩展公式count = count + 1,这会将count设为equal本身+ 1

count = count + 1

答案 1 :(得分:2)

如果要计算每次迭代中的数字:

for i in range(5):
   for j in range(5):
       count = 5*i+j+1
       print count

答案 2 :(得分:2)

The mysterious formula is quite simple:

{count} = {index of current loop} + {size of current loop}*{count of parent loop}

As an example, consider a single loop:

x = 5

for i in range(x):
    count = i

To be explicit, count = i + x*0 but the second term is irrelevant because there is no parent loop. An example of two loops might be more illuminating:

x = 5
y = 6

for i in range(x):
    for j in range(y):
        count = j + y*(i)

Notice that I put i in parentheses to emphasize that it is the {count of parent loop}. This formula can be easily expanded to a third loop:

x = 5
y = 6
z = 7

for i in range(x):
    for j in range(y):
        for k in range(z):
            count = k + z*(j + y*(i))

and so on...

答案 3 :(得分:0)

最简单的方法是使用itertools.productenumerate

from itertools import product

for idx, (i, j) in enumerate(product(range(5), range(5)), 1):
    print(idx, i, j)

打印:

1 0 0
2 0 1
3 0 2
4 0 3
5 0 4
[...]
24 4 3
25 4 4