简体   繁体   English

python中具有多个循环和if语句的列表理解

[英]List comprehension in python with multiple loops and if statements

I have to print a list of ordered pairs where x+y+z != n. 我必须打印一个有序对的列表,其中x + y + z!= n。 The code doesn't seem to be working 该代码似乎不起作用

def main():
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    result = [[i,j,k] for i in range(0,x+1) for j in range(0,y+1) for k in range(0,z+1) if (x+y+z) != n]
    print(result)

Input: 输入:

1
1
1
2

Output: 输出:

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

I shouldn't be getting the ordered pairs [0,1,1] , [1,0,1], [1,1,0]. 我不应该得到有序对[0,1,1],[1,0,1],[1,1,0]。

Please correct me. 请纠正我。

Thanks in advance! 提前致谢!

You mixed the list comprehension variables with the inputs from the user. 您将列表理解变量与用户输入混合在一起。

Replace: 更换:

if (x+y+z) != n

with

if (i+j+k) != n

One liners are great, but they can confuse me, so I will expand your code 一个内衬很好,但是它们会使我困惑,所以我将扩展您的代码

    result = []
    for i in range(0, x+1):
        for j in range(0, y+1):
            for k in range(0, z+1):
                if (i+k+j)!=n:
                    result.append([i,k,j])

And it works for me 对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM