Nested for-loop: why does the inner loop execute only once?

I am confused about using double for loop in python, this is my code:

import numpy as np

range1 = np.linspace(1,6,10)
range2 = reversed(np.linspace(1,6,10))

for t1 in range1:
    print t1
    for t2 in range2:
        print t1,t2

Conclusion:

1.0
1.0 6.0
1.0 5.44444444444
1.0 4.88888888889
1.0 4.33333333333
1.0 3.77777777778
1.0 3.22222222222
1.0 2.66666666667
1.0 2.11111111111
1.0 1.55555555556
1.0 1.0
1.55555555556
2.11111111111
2.66666666667
3.22222222222
3.77777777778
4.33333333333
4.88888888889
5.44444444444
6.0

It only executes the inner loop for the first value of the outer loop, why is this happening? How can I make it iterate over all combinations of the first and second variables?

+4
source share
3 answers

reversed()creates an iterator; once you reach the end of the iterator, you cannot reuse it:

>>> it = reversed([1, 2, 3])
>>> list(it)
[3, 2, 1]
>>> list(it)
[]

Create a new iterator for the nested loop:

for t1 in range1:
    print t1
    for t2 in reversed(range1):
        print t1,t2

reversed()documentation of a link to an iterator glossary entry :

, StopIteration. , __next__() StopIteration.

.

+10

, pythons, reversed ( , ). , yield - . :

range2 = np.linspace(1,6,10)[::-1]

for t1 in range1:
    print t1
    for t2 in range2:
        print t1,t2

numpy.array , .

, array, , , unboxed. array (: ), list s:

range1 = np.linspace(1,6,10).tolist()
range2 = np.linspace(1,6,10)[::-1].tolist()

tolist () ​​for -loop.

+4

reversed . .

.

, list:

import numpy as np

range1 = np.linspace(1,6,10)
range2 = list(reversed(np.linspace(1,6,10)))  # store in list

for t1 in range1:
    print t1
    for t2 in range2:
        print t1,t2

, . 1 [0, 1, ..., 1000000], , .

In the simple case, as in OP, the list is short, and you know that you will iterate over all elements, so using the list is quite simple and efficient.

+2
source

Source: https://habr.com/ru/post/1675447/


All Articles