python - 嵌套 for 循环 : why is the inner loop only executed once?

标签 python loops for-loop nested reverse

我对在 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 raise StopIteration again.

大胆强调我的。

关于python - 嵌套 for 循环 : why is the inner loop only executed once?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572580/

相关文章:

python - 将 .txt 中的行读取到批处理文件中并作为参数传递到命令行?

python - 使用 python 的 networkX 计算个性化页面排名

Ruby:for 循环和 each 循环有什么区别?

loops - Else If 是否为 FileExists()

javascript - Node - 等待循环完成?

C 无限循环(IF 嵌套在 FOR LOOP 中)

python - Django 表单发布未获取 request.GET 中的值

python - 具有数据源动态更新的 Bokeh 应用程序

无法打印在循环中递增的变量值

php - 具有自定义索引 PHP 的 Foreach