为什么只有这些嵌套while循环的最里面工作?

时间:2012-03-31 13:33:02

标签: python while-loop

我是Python的新手。 我有这个简单的代码

a = 0
b = 0
c = 0

while a <= 5:
    while b <=3:
        while c <= 8:
            print a , b , c
            c += 1
        b += 1
    a += 1

只有在使用C

时才能工作
0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
0 0 6
0 0 7
0 0 8

为什么呢?怎么解决? 谢谢!

4 个答案:

答案 0 :(得分:7)

第一种方式

您的方式可行,但您必须记住在每次迭代时重置循环计数器。

a = 0
b = 0
c = 0

while a <= 5:
    while b <=3:
        while c <= 8:
            print a , b , c
            c += 1
        b += 1
        c = 0 # reset
    a += 1
    b = 0 # reset
    c = 0 # reset

第二种方式(Pythonic)

第一种方式涉及大量簿记。在Python中,在一系列数字上指定循环的更简单方法是在for *迭代器上使用xrange循环:

for a in xrange(5+1): # Note xrange(n) produces 0,1,2...(n-1) and does not include n.
    for b in xrange (3+1):
        for c in xrange (8+1):
            print a,b,c
  • 注意:在Python 3中,xrange现在称为range。 (或者更准确地说,Python 3 range取代了Python 2.x的rangexrange。)

第三种方式(最佳)

第二种方法可以通过itertools.product()的应用来简化,import itertools for a,b,c in itertools.product(xrange(5+1),xrange(3+1),xrange(8+1)): print a,b,c 接受一些迭代(列表)并返回每个列表中每个元素的每个可能组合。

{{1}}

对于这些技巧等,请阅读Dan Goodger's "Code Like a Pythonista: Idiomatic Python"

答案 1 :(得分:6)

您忘记分别在bc的循环顶部重置ab。这就是我们使用for循环的原因。

答案 2 :(得分:2)

c <= 8c <= 8时被循环,所以c到达8,因此程序永远不必再次执行该循环。

尝试在循环结束时设置c = 0,并在循环后将ba设置为0,或者更好地使用itertools或for循环。

答案 3 :(得分:0)

在第一个while循环之后c将等于9.你永远不会重置c所以,c <= 8在a或b循环中永远不会为真。

如果在循环之前重置每个循环,它将正常工作。

a = 0
while a <= 5:
    b = 0
    while b <=3:
        c = 0
        while c <= 8:
            print a , b , c
            c += 1
        b += 1
    a += 1