使用Pandas/Regex在Python中基于运算符将单行拆分为多行
基于OR运算符拆分复杂逻辑条件的实现方案
要实现将包含OR运算符的复杂逻辑条件拆分为多个独立简单条件,核心是处理括号优先级下的OR拆分,并对AND结构做笛卡尔积组合,以下是具体实现步骤和代码(以Python为例):
核心思路
- 识别顶级运算符:区分括号内外的AND/OR,仅处理顶级(不在括号内)的运算符,避免破坏嵌套逻辑。
- 递归拆分OR分支:对每个包含OR的逻辑块,递归拆分为独立的子条件。
- 笛卡尔积组合AND项:如果条件是多个AND项的组合,每个AND项拆分OR后,通过笛卡尔积生成所有可能的组合。
代码实现
辅助函数:查找顶级OR位置
定位字符串中不在括号内的or运算符位置:
def find_top_level_or(s): stack = [] for i in range(len(s)): if s[i] == '(': stack.append('(') elif s[i] == ')': stack.pop() elif s[i:i+4] == ' or ' and not stack: return i return -1
辅助函数:拆分顶级AND项
将条件拆分为多个顶级AND连接的子项:
def split_top_level_and(s): stack = [] parts = [] start = 0 for i in range(len(s)): if s[i] == '(': stack.append('(') elif s[i] == ')': stack.pop() elif s[i:i+5] == ' and ' and not stack: parts.append(s[start:i].strip()) start = i+5 parts.append(s[start:].strip()) return parts
递归拆分OR条件
递归处理所有OR分支,返回所有独立子条件:
def split_condition(cond): or_pos = find_top_level_or(cond) if or_pos == -1: return [cond.strip()] left = cond[:or_pos].strip() right = cond[or_pos+4:].strip() return split_condition(left) + split_condition(right)
扩展复杂条件
结合AND项拆分和OR分支拆分,生成所有可能的简单条件:
from itertools import product def expand_condition(cond): # 拆分为顶级AND子项 and_parts = split_top_level_and(cond) part_options = [] for part in and_parts: # 处理带外层括号的OR块 if part.startswith('(') and part.endswith(')'): inner = part[1:-1].strip() options = split_condition(inner) # 给拆分后的子项补回括号,保持结构一致性 options = [f"({opt})" if not (opt.startswith('(') and opt.endswith(')')) else opt for opt in options] else: options = split_condition(part) part_options.append(options) # 生成笛卡尔积并拼接成新条件 expanded = [] for combo in product(*part_options): expanded.append(' and '.join(combo)) return expanded
处理表格数据
将输入的条件-结果对批量转换为拆分后的格式:
# 示例输入数据 input_data = [ {"condition": "((a and b) or (c and d))", "result": "Result A"}, {"condition": "(a or b or c) and ( d and e) and (x or (y and z))", "result": "Result B"} ] output_data = [] for item in input_data: for cond in expand_condition(item["condition"]): output_data.append({"condition": cond, "result": item["result"]}) # 打印输出表格 print("| condition | result |") print("| -------- | -------- |") for row in output_data: print(f"| {row['condition']} | {row['result']} |")
输出结果
运行上述代码后,会生成符合需求的表格:
| condition | result | | -------- | -------- | | (a and b) | Result A | | (c and d) | Result A | | (a) and ( d and e) and (x) | Result B | | (a) and ( d and e) and (y and z) | Result B | | (b) and ( d and e) and (x) | Result B | | (b) and ( d and e) and (y and z) | Result B | | (c) and ( d and e) and (x) | Result B | | (c) and ( d and e) and (y and z) | Result B |
内容的提问来源于stack exchange,提问作者Shaikh Shoeb
相关产品推荐
相关产品推荐

