简体   繁体   中英

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:

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

 (not p) or q

It uses at as a string. 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 . 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:

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. What's more eval is slow. So this answer can probably be enhanced.

More information about eval here: Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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