我正在尝试构建一个由Pandas查询处理的查询生成器。下面是结构。
{ ["AND", ["OR", ["AND", {
"Property": "ColumnA",
"Operand": ">",
"Value": "56"
}, {
"Property": "ColumnA",
"Operand": "<",
"Value": "78"
}],
["AND", {
"Property": "ColumnA",
"Operand": "==",
"Value": "99"
}]
], {
"Property": "ColumnB",
"Operand": "==",
"Value": "true"
}]
}
所以结果应该是这样的,如果与单个对象关联,我们将忽略条件,否则将与其他结果连接
((ColumnA > 56 and ColumnA < 78) or ColumnA == 99) and ColumnB == true)
下面是我正在尝试的
下面的函数获取类型
def represents_number(s):
try:
number = float(s) if float(s) else int(s)
return number
except ValueError:
return False
def represents_boolean(s):
if s.lower() in ("false", "true"):
if s.lower() == "true":
return True
else:
return False
else:
return 'error'
def check_type(value):
boolean_type = represents_boolean(value)
if boolean_type != 'error':
return boolean_type
else:
num = represents_number(value)
if type(num) is float:
return num
else:
return f'{value}'
该函数创建条件字符串
def get_query_string(query: dict):
if query['Value'] == 'null':
new_condition = f" {query['Property']}.isnull()"
return new_condition
value = check_type(query['Value'])
if isinstance(value, str):
new_condition = f" {query['Property']} {query['Operand']} '{value}' "
else:
new_condition = f" {query['Property']} {query['Operand']} {value} "
return new_condition
如果存在对象列表,此函数将建立条件
def build_condition(lst, join_condition):
query_string = ''
condition = []
for item in lst:
if isinstance(item, dict):
condition.append(get_query_string(item))
query_string = join_condition.join(condition)
query_string = '({})'.format(query_string)
return query_string
最后,我试图创建这个函数来构建最终的查询
join_conditions = []
def Process(lst, query):
global join_conditions
for idx, x in enumerate(lst):
if isinstance(x, list):
if len(x) > 2 and isinstance(x[1], dict) and isinstance(x[2], dict):
join_condition = join_conditions[idx]
condition = build_condition(x, x[0])
query = f"{query} {join_condition} {condition}"
else:
Process(x, query)
elif isinstance(x, dict) and query == '' and len(lst) == 2:
condition = get_query_string(x)
query = condition
elif isinstance(x, dict):
#code here
else:
join_conditions.append(x)
return query
我正在努力的是关联条件加入2叶节点。这里需要指引谢谢
根据@Andrew的建议,使用while循环创建了一个字典,而不是重新组合,这有助于我确定联接的位置。