我可以循环遍历 python 中的逻辑运算符吗?
Can I loop through logical operators in python?
为了避免重复,我想做这样的事情:
a, b = True, False
l = list()
for op in [and, or, xor]:
l.append(a op b)
我尝试了 import operator
和 itertools
,但它们不包含逻辑运算符,只有数学和其他一些运算符。
我找不到任何以前有用的答案!
or
和 and
不能真正被函数复制,因为它们 short-circuit;但如果你不关心,你可以编写 lambda 函数,例如lamba x, y: x and y
。对于布尔值的异或运算,您可以使用 operator.ne
.
ops = [(lambda x,y: x and y), (lambda x,y: x or y), operator.ne]
l = [op(a,b) for op in ops]
Adrian W 在评论中建议列表理解。
更新:使用。比较好。
您的示例可以使用 operator
模块来实现。
from operator import and_, or_, xor
ops = [and_, or_, xor]
l = [op(a,b) for op in ops]
这些是按位运算符,但对于仅用一位表示的布尔值,它们兼作逻辑运算符。
为了避免重复,我想做这样的事情:
a, b = True, False
l = list()
for op in [and, or, xor]:
l.append(a op b)
我尝试了 import operator
和 itertools
,但它们不包含逻辑运算符,只有数学和其他一些运算符。
我找不到任何以前有用的答案!
or
和 and
不能真正被函数复制,因为它们 short-circuit;但如果你不关心,你可以编写 lambda 函数,例如lamba x, y: x and y
。对于布尔值的异或运算,您可以使用 operator.ne
.
ops = [(lambda x,y: x and y), (lambda x,y: x or y), operator.ne]
l = [op(a,b) for op in ops]
Adrian W 在评论中建议列表理解。
更新:使用
您的示例可以使用 operator
模块来实现。
from operator import and_, or_, xor
ops = [and_, or_, xor]
l = [op(a,b) for op in ops]
这些是按位运算符,但对于仅用一位表示的布尔值,它们兼作逻辑运算符。