使用3个条件过滤出数组中的值

问题描述 投票:0回答:2

我想过滤出数组中满足3个条件的值,如下面的示例所示。

a = [0 1 2 3 4 5]
condition1 states a > 0
condition2 states a is even 
condition3 states a = 1

applying condition1 & condition2 & condition3 gives 
a = [0 3 5]

问题是我不能只是a[(a > 0) & (a is even) & (a = 1)],因为那会返回我要删除的值的数组,而a[(a <= 0) or (a is odd) or (a != 1)]不会返回我要寻找的值。

我该如何去做?

python
2个回答
0
投票

首先,您没有提供最低限度的工作示例。

此行是错误的

这样的事情。

a = [0 1 2 3 4 5]
b = [i for i in a if i > 0 and i % 2 == 0 and i == 1]

-1
投票

如@ferhen所述,条件是矛盾的,因此它将返回一个空列表,但您可以执行此操作

a = [elem for elem in a if elem > 0 and elem % 2 == 0 and elem == 1]

0
投票

我不确定如何解析您的逻辑规范,但这会提供您想要的输出。

>>> L = [0, 1, 2, 3, 4, 5]
>>> [x for x in L if x > 0 and x % 2 or x == 1]
[1, 3, 5]
© www.soinside.com 2019 - 2024. All rights reserved.