简体   繁体   English

我可以循环遍历python中的逻辑运算符吗?

[英]Can I loop through logical operators in python?

In order to avoid repetition, I would like to do something like this:为了避免重复,我想做这样的事情:

a, b = True, False
l = list()
for op in [and, or, xor]:
    l.append(a op b)

I tried import operator and also itertools , but they do not contain logical operators, just math and some other ones.我尝试了import operatoritertools ,但它们不包含逻辑运算符,只包含数学和其他一些运算符。

I could not find any previous answer that was helpful!我找不到任何有用的先前答案!

Your example can be implemented using the operator module.您的示例可以使用operator模块来实现。

from operator import and_, or_, xor

ops = [and_, or_, xor]
l = [op(a,b) for op in ops]

These are bitwise operators, but for booleans -- which are represented in only one bit -- they double as logical operators.这些是按位运算符,但对于仅用一位表示的布尔值而言,它们兼作逻辑运算符。

or and and can't really be replicated by functions because they short-circuit; orand不能真正被函数复制,因为它们是短路的; but if you don't care about that you can write lambda functions, eg lamba x, y: x and y .但如果你不在乎,你可以编写 lambda 函数,例如lamba x, y: x and y For xor on booleans you could use operator.ne .对于布尔值的异或,您可以使用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]

The list comprehension was suggested by Adrian W in the comments. Adrian W 在评论中建议使用列表理解。

Update: Use stfwn's answer .更新:使用stfwn 的回答 It's better.更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM