列出理解头痛

Rob*_*dra 4 python list-comprehension

我有一个这样的嵌套列表:

list = [[1,2,3], [2,5,7,6], [1,-1], [5,7], [6,3,7,4,3], [2, 5, 1, -5]]
Run Code Online (Sandbox Code Playgroud)

我想做的是删除嵌套列表,这些列表中的值既是正数也是负数。我已经尝试通过列表理解来做到这一点,但是我无法弄清楚。

def method(list):
    return [obj for obj in list if (x for x in obj if -x not in obj)]
Run Code Online (Sandbox Code Playgroud)

获得的结果应类似于:

 list = [[1,2,3], [2,5,7,6], [5,7], [6,3,7,4,3]]
Run Code Online (Sandbox Code Playgroud)

650*_*502 5

假设您想要列出元素全部为负或全部为正的列表,则可以使用all预定义功能来检查这两种可能性

result = [L for L in x if all(y>0 for y in L) or all(y<0 for y in L)]
Run Code Online (Sandbox Code Playgroud)

编辑:

在注释中,您阐明了什么是有效列表(例如,有效列表[-1, 2])...使用此新公式,测试应为

result = [L for L in x if all(-y not in L for y in L)]
Run Code Online (Sandbox Code Playgroud)

但是,每个测试的列表大小现在都是平方的。使用set这个问题可以消除

result = [L for L in x if all(-y not in S for S in (set(L),) for y in L)]
Run Code Online (Sandbox Code Playgroud)