Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension headaches

I have a nested list like this which:

list = [[1,2,3], [2,5,7,6], [1,-1], [5,7], [6,3,7,4,3], [2, 5, 1, -5]]

What I am trying to do is to remove nested lists, where the value within these lists are both positive and negative. I have tried doing it by list comprehension, but I couldn't figure it out.

def method(list):
    return [obj for obj in list if (x for x in obj if -x not in obj)]

The obtained results should be like:

 list = [[1,2,3], [2,5,7,6], [5,7], [6,3,7,4,3]]
like image 734
Robert Avatar asked Dec 13 '22 10:12

Robert


1 Answers

Assuming you want lists where elements are either all negative or all positive you can use all predefined function to check for both possibilities

result = [L for L in x if all(y>0 for y in L) or all(y<0 for y in L)]

EDIT:

In the comments you clarified what is a valid list (e.g. [-1, 2] is valid)... with this new formulation the test should be

result = [L for L in x if all(-y not in L for y in L)]

where each single test is however now quadratic in the size of the list. Using set this problem can be removed

result = [L for L in x if all(-y not in S for S in (set(L),) for y in L)]
like image 54
6502 Avatar answered Dec 15 '22 23:12

6502