我是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
为什么呢?怎么解决? 谢谢!
答案 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
第一种方式涉及大量簿记。在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
xrange
现在称为range
。 (或者更准确地说,Python 3 range
取代了Python 2.x的range
和xrange
。)第二种方法可以通过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)
您忘记分别在b
和c
的循环顶部重置a
和b
。这就是我们使用for
循环的原因。
答案 2 :(得分:2)
当c <= 8
在c <= 8
时被循环,所以c
到达8
,因此程序永远不必再次执行该循环。
尝试在循环结束时设置c = 0
,并在循环后将b
和a
设置为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