如果元素不遵循“if”或“语句”,则从列表中删除元素 [英] Deleting elements from a list if they do not follow 'if' 'or' statements
问题描述
我试图摆脱列表中不需要的变量。我需要有两个条件:一个是确保我的数组中的值小于变量A,另一个是确保它们不等于另一个变量B.
I am trying to get rid of unwanted variables in a list. I need to have two condition: one is if making sure the values in my array are smaller than a variable A, and the other is making sure they are not equal to another variable B.
此代码不起作用:
original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
new_Ar = [s for s in original_Ar if (s != 2) or (s < 10)]
print (new_Ar)
如果我把它分成两个语句(而不是或
声明) - 它们确实有效:
while if I split it into two statements (instead of the or
statement) - they do work:
original_Ar = [0,1,2,3,4,5,6,7,8,9,10,11,12]
print ([s for s in original_Ar if (s != 2)])
print ([s for s in original_Ar if (s < 10)])
我知道怎么能在一行中做到这一点?
Any idea how can I do that in one line?
推荐答案
你的布尔逻辑混淆了。您希望包含的所有值不等于2 且小于10:
You have your boolean logic mixed up. You want to include all values that are not equal to 2 and are smaller than 10:
new_Ar = [s for s in original_Ar if s != 2 and s < 10]
# *both* conditions must be true ^^^
否则,你' d包括 s = 2
,因为它小于10,并且你包括 s = 11
和 s = 12
,因为两者都不等于两个!
Otherwise, you'd include s = 2
, because it is smaller than ten, and you'd include s = 11
and s = 12
, because both are not equal to two!
这篇关于如果元素不遵循“if”或“语句”,则从列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!