【问题标题】:Do nested for loops in python work unlike they do in C?python中的嵌套for循环与C中的工作方式不同吗?
【发布时间】: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


【解决方案1】:

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]

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 2017-05-13
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多