如何在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)]
。
答案 0 :(得分:3)
range()
有一个非包含上限。 list(range(1))
是[0]
-不是[0,1]
:
您得到
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 1, 1)]
如果您更改
for a in range(x+1): # add 1 here
for b in range(y+1): # and here
for c in range(z+1): # and here
# ect
您的列表中仍将有元组-因为您添加了元组而不是其中的列表:
num_list.append((a,b,c)) # this adds a tuple (a,b,c) not a list [a,b,c]
您可以通过列表理解获得相同的结果:
num_list= [(a,b,c) for a in range(x+1) for b in range(y+1) for c in range(z+1)
if a+b+c != n]