我有一个像这样的嵌套列表:
list = [[1,2,3], [2,5,7,6], [1,-1], [5,7], [6,3,7,4,3], [2, 5, 1, -5]]
我想做的是删除嵌套列表,这些列表中的值都是正数和负数。我已经尝试通过列表理解来做到这一点,但是我无法弄清楚。
def method(list):
return [obj for obj in list if (x for x in obj if -x not in obj)]
获得的结果应该像:
list = [[1,2,3], [2,5,7,6], [5,7], [6,3,7,4,3]]
您可以做:
def positives(ls):
return set(l for l in ls if l > 0)
def negatives(ls):
return set(-1*l for l in ls if l < 0)
list = [[1, 2, 3], [2, 5, 7, 6], [1, -1], [5, 7], [6, 3, 7, 4, 3], [2, 5, 1, -5]]
result = [l for l in list if not negatives(l) & positives(l)]
print(result)
输出
[[1, 2, 3], [2, 5, 7, 6], [5, 7], [6, 3, 7, 4, 3]]