在Python表达式中使用字符串(表示逻辑运算符) [英] Use a string (representing a logical operator) in a Python expression

查看:853
本文介绍了在Python表达式中使用字符串(表示逻辑运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以某种方式将一个字符串(例如转换为可识别的表单作为一个逻辑运算符?

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

其中 o [item1] code>被识别为有效的逻辑运算符

推荐答案

p>您可以使用运算符包:

import operator

o = {item1: operator.or_}

if o[item1](i>4, i<0):
    ...

请注意,或_ 不会短路,如。如果您真的需要短路行为,可以使用 eval (但一般不推荐)。

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).

这篇关于在Python表达式中使用字符串(表示逻辑运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆