简体   繁体   English

如何编写给定代码的列表推导?

[英]How do i write the list comprehension for the given code?

I am fairly new to python. 我对python很新。

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

I tried it by : 我尝试过:

l = [[[i for i in range(x+1)] for j in range(y+1)] for k in range(z+1) if i+j+k != n]

but it isn't working. 但它不起作用。

@e4c5 provides the literal replacement but you can use itertools to simplify the comprehension. @ e4c5提供了文字替换,但您可以使用itertools来简化理解。 In particular itertools.product() would give you the equivalent of the nested for loops: 特别是itertools.product()会给你相当于嵌套的for循环:

import itertools as it
[a for a in it.product(range(x+1), range(y+1), range(z+1)) if sum(a) != n]

Nested list comprehensions can be a bit tricky. 嵌套列表推导可能有点棘手。 You need a three tuple to be appended to your list. 您需要将三元组添加到列表中。 So that means the first part of the comprehension should be (i,j,k) 这意味着理解的第一部分应该是(i,j,k)

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

Then you need that append to be list to be conditional upon i+j+k not being equal to n. 然后你需要将list作为条件,以i + j + k不等于n为条件。 To the if condition comes at the end. 结果是if条件。 There shouldn't be any other [ or ] in between. 中间不应该有任何其他[]

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

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