【发布时间】:2019-04-19 14:38:57
【问题描述】:
如何在 Python 中使用嵌套的 for 循环,就像我们在 C 中通常使用的那样?
我正在处理一个需要三个输入然后是一个数字的问题。程序应该返回 3 个整数的集合,每个整数的值都达到我们作为输入提供的各自值,其总和不等于我们作为输入提供的第四个数字。
我尝试使用三个嵌套的 for 循环,每个循环都在我们作为输入提供的三个整数值的范围内进行迭代。但是,我的程序在仅给出第一个 [0,0,0] 组合后停止。
x = int(input())
y = int(input())
z = int(input())
n = int(input())
num_list=[]
for a in range(x):
for b in range(y):
for c in range(z):
if a+b+c==n:
continue
else:
num_list.append((a,b,c))
print(num_list)
如果输入是1, 1, 1, 2,那么程序应该返回[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]],但我的输出是[(0,0,0)]。
【问题讨论】:
-
Range(1) 是 exclusive 数字 1,所以它只产生 0。你想要 range(x+1) 等等。
标签: python python-3.x