[英]I have a list of lists containing boolean values. How can I input a boolean function and check it in every sublist of my list?
Here's what i am trying to do.这就是我想要做的。 I am basically having a truth-table for two boolean formulas:
我基本上有两个 boolean 公式的真值表:
x=[True, False]
y=[True, False]
a=[]
for i in x:
for z in y:
a.append([i, z])
Now I want to input some boolean expression and check it in every "row" of my truth-table.现在我想输入一些 boolean 表达式并在我的真值表的每一“行”中检查它。 I tried this:
我试过这个:
p=None
q=None
result=[]
exp=input("Type your boolean expression using p and q as variables: ")
for i in a:
p, q = i[0], i[1]
result.append(exp)
print(result)
But when I try to type some boolean expression as input, for example:但是当我尝试输入一些 boolean 表达式作为输入时,例如:
(not p) or q
It uses at as a string.它使用 at 作为字符串。 But if I do this:
但如果我这样做:
exp=bool(input("Type your boolean expression using p and q as variables: "))
then every non-empty string would be regarded as True
in bool
.那么每个非空字符串在
bool
中都将被视为True
。 How can I solve this?我该如何解决这个问题?
From what you said I understand that you want to apply a hand written expression to all elements of a list.根据您所说的,我了解到您想将手写表达式应用于列表的所有元素。
If your table is always 2-element wide you can go with:如果你的表总是 2 元素宽,你可以使用 go:
table = [[True, True], [False, True], [True, False]]
expression = 'p and q'
[eval(expression) for p, q in table]
# Output
[True, False, False]
However your expression need to respect Python syntax.但是,您的表达式需要遵守 Python 语法。 What's more eval is slow.
更重要的是 eval 很慢。 So this answer can probably be enhanced.
所以这个答案可能会得到加强。
More information about eval here: Documentation有关 eval 的更多信息,请参见:文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.