是否可以在dict文字中包含“可选”键,而不是在if语句中添加它们?
像这样:
a = True
b = False
c = True
d = False
obj = {
"do_a": "args for a" if a,
"do_b": "args for b" if b,
"do_c": "args for c" if c,
"do_d": "args for d" if d,
}
#expect:
obj == {
"do_a": "args for a",
"do_c": "args for c",
}
编辑上下文:我知道如何执行逻辑:)我只是想避免使用if语句,因为我的对象是代表声明性逻辑的大数据块,因此移动内容有点像“意大利面条式编码”,不是意味着完全是程序性的。我希望对象的值“看起来像是什么意思”作为查询。
它实际上是一个Elasticsearch查询,因此它将如下所示:
{
"query": {
"bool": {
"must": [
<FILTER A>,
<FILTER B>, # would like to make this filter optional
<FILTER C>,
{
"more nested stuff" : [ ... ]
}
],
"other options": [ ... ]
},
"other options": [ ... ]
},
"other options": [ ... ]
}
而我可能会怀疑的目标是使它看起来像一个查询,您可以查看它并了解它的形状,而不必通过ifs进行跟踪。即,没有“过滤器”:[f中的f为过滤器中的f,如果启用f。],因为然后您必须去寻找过滤器,无论如何,这些过滤器都是可选常数
蓝山帝景
相关分类