首页 > 解决方案 > 如何在str()中取python条件表达式

问题描述

代码 python 3.6

#database contains rows (relationships) of the form:
# (autoincremented id, booleans, column3, column4)
# ejm: (1, "A || B || C", "data1", "data2")


def function (booleans):
     global list1
     global list2

     '' 'takes `booleans` and queries the database to retrieve
        column3, and column4 '' '

     list1 = column3
     list2 = column4

     return list1, list2


if A:
     if B:
         if C:
             function ('A || B || C')
         elif D:
             function ('A || B || D')
     elif E:
         if C:
             function ('A || E || C')
        
print (list1)
print (list2)

# this is olnly an example
#if `B` is `False` then `E` would have to be `True`

该程序将仅根据情况在条件句中选择一条路径,并将打印由布尔值分配的列表。

所以问题是,如何在不在条件句中手动执行的情况下自动将参数赋予函数(bool)?. sds

标签: pythonconditional-statements

解决方案


不确定我是否正确理解了这个问题,但如果我理解了,最好的办法是用字典替换你的单独变量等AB

dic = {}
dic['A'] = True
dic['B'] = False
dic['C'] = True
# etc.
s = ' || '.join([k for k, v in dic.items() if v]) 
# for the above data, s is now 'A || C' 
function(s)

推荐阅读