Yai*_*air 1 python if-statement
我试图摆脱列表中不需要的变量.我需要有两个条件:一个是确保我的数组中的值小于变量A,另一个是确保它们不等于另一个变量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)
Run Code Online (Sandbox Code Playgroud)
如果我将它分成两个语句(而不是or语句) - 它们确实有效:
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)])
Run Code Online (Sandbox Code Playgroud)
知道我怎么能在一行中做到这一点?
你的布尔逻辑混淆了.您希望包含所有不等于2 且小于10的值:
new_Ar = [s for s in original_Ar if s != 2 and s < 10]
# *both* conditions must be true ^^^
Run Code Online (Sandbox Code Playgroud)
否则,你有s = 2,因为它是十小,你有s = 11和s = 12,因为两者都是不等于二!