我对在 python 中使用双 for 循环感到困惑,这是我的代码:
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
输出是这样的:
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
它只对外循环的第一个值执行内循环,为什么会这样?我怎样才能让它遍历第一个和第二个变量的所有组合?
最佳答案
reversed()
产生一个迭代器;一旦到达迭代器的末尾,就不能重新使用它:
>>> it = reversed([1, 2, 3])
>>> list(it)
[3, 2, 1]
>>> list(it)
[]
为嵌套循环创建一个新的迭代器:
for t1 in range1:
print t1
for t2 in reversed(range1):
print t1,t2
reversed()
documentation链接到 iterator glossary entry :
When no more data are available a
StopIteration
exception is raised instead. At this point, the iterator object is exhausted and any further calls to its__next__()
method just raiseStopIteration
again.
大胆强调我的。
关于python - 嵌套 for 循环 : why is the inner loop only executed once?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572580/