I'm trying to check if a list has no member as boolean operator AND, OR, NOT.
I use:
while ('AND' a开发者_JAVA百科nd 'OR' and 'NOT') not in list:
print 'No boolean operator'
However, when my input is: a1 c2 OR c3 AND
, it prints 'No boolean operator', which means this list is considered no boolean operator in it by using above loop sentence.
Hope somebody can help to correct.
Thanks, Cindy
Using sets
will be screaming fast if you have any volume of data
If you are willing to use sets, you have the isdisjoint()
method which will check to see if the intersection between your operator list and your other list is empty.
MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])
while not MyList.isdisjoint(MyOper):
print "No boolean Operator"
http://docs.python.org/library/stdtypes.html#set.isdisjoint
The expression 'AND' and 'OR' and 'NOT'
always evaluates to 'NOT'
, so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
and
ing strings does not do what you think it does - use any to check if any of the strings are in the list:
while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
print 'No boolean'
Also, if you want a simple check, an if
might be better suited than a while
...
The expression ('AND' and 'OR' and 'NOT')
evaluates to 'NOT'
, so you are testing whether the list has NOT or not.
while not any( x in ('AND','OR','NOT') for x in list)
EDIT:
thank you for the upvotes , but etarion's solution is better since it tests if the words AND, OR, NOT are in the list, that is to say 3 tests.
Mine does as many tests as there are words in list.
EDIT2:
Also there is
while not ('AND' in list,'OR' in list,'NOT' in list)==(False,False,False)
If I understand the question correctly you are looking for something like this:
>>> s = "a1 c2 OR c3 AND"
>>> boolops = ["AND", "OR", "NOT"]
>>> if not any(boolop in s for boolop in boolops):
... print "no boolean operator"
...
>>> s = "test"
>>> if not any(boolop in s for boolop in boolops):
... print "no boolean operator"
...
no boolean operator
>>>
That's not how it works.
This bit ('AND' and 'OR' and 'NOT')
will evaluate as 'NOT'
. So your code is equivalent to::
while not 'NOT' in list: print 'No boolean operator'
You could try this:
while not set('AND' and 'OR' and 'NOT').union(list): print 'No boolean operator'
In your case, ('AND' and 'OR' and 'NOT')
evaluates to "NOT"
, which may or may not be in your list...
while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
print 'No Boolean Operator'
精彩评论