如何使用:while not in
我想检查一个列表里是否没有布尔运算符,比如 AND、OR 和 NOT。
我用的是:
while ('AND' and 'OR' and 'NOT') not in list:
print 'No boolean operator'
但是,当我的输入是:a1 c2 OR c3 AND
时,它却打印出'没有布尔运算符',这意味着在我用的这个循环里,这个列表被认为没有布尔运算符。
希望有人能帮我纠正一下。
谢谢,
Cindy
8 个回答
3
把字符串用and
连接起来并不是你想的那样 - 用any
来检查列表中是否有任何一个字符串:
while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
print 'No boolean'
另外,如果你想做一个简单的检查,使用if
可能比用while
更合适...
4
这个表达式 'AND' and 'OR' and 'NOT'
总是会得到 'NOT'
,所以实际上你是在做
while 'NOT' not in some_list:
print 'No boolean operator'
你可以单独检查它们每一个
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
或者使用集合
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
7
如果你使用sets
,处理大量数据会非常快
如果你愿意使用集合(sets),你可以用isdisjoint()
这个方法来检查你的操作列表和另一个列表之间是否没有交集,也就是说它们是否没有共同的元素。
MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])
while not MyList.isdisjoint(MyOper):
print "No boolean Operator"