问题
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.
This code dose not work:
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?
回答1:
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 ^^^
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!
来源:https://stackoverflow.com/questions/41984283/deleting-elements-from-a-list-if-they-do-not-follow-if-or-statements