Is it possible to somehow cast a string of, say, or or and into a form that is recognizable as a logical operator?
For example, is it possible to do something like this:
l = [1, 2, 3, 4, 5]
o = {item1:'or'}
for i in l:
if i > 4 o[item1] i < 0:
print i
where o[item1] is recognized as a valid or logical operator?
解决方案
You may use the operator package:
import operator
o = {item1: operator.or_}
if o[item1](i>4, i<0):
...
Note that or_ does not short-circuit, like or does. If you really need the short-circuit behaviour, you can use eval (but this is in general not recommended).