Deleting elements from a list if they do not follow 'if' 'or' statements

守給你的承諾、 提交于 2020-01-05 05:59:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!