How do i write the list comprehension for the give

2019-07-13 03:38发布

问题:

I am fairly new to 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.

回答1:

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) 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. To the if condition comes at the end. There shouldn't be any other [ or ] in between.



回答2:

@e4c5 provides the literal replacement but you can use itertools to simplify the comprehension. In particular itertools.product() would give you the equivalent of the nested for loops:

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