使用python中的Pandas / regex基于运算符从单行创建多行

kt06eoxx  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(96)

我有一个数据,其中有很多行,像这样:

| condition                                          | result |
| --------                                           | -------- |
| ((a and b) or (c and d))                           | Result A  |
| (a or b or c) and ( d and e) and (x or (y and z))  | Result B  |

我想把它们转换成

| condition                                    | result |
| --------                                     | -------- |
| (a and b)                                    | Result A  |
| (c and d)                                    | Result A  |
| (a) and ( d and e) and (x)                   | Result B  |
| (b) and ( d and e) and (x)                   | Result B  |
| (c) 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 (y and z)             | Result B  |
| (c) and ( d and e) and (y and z)             | Result B  |

所有条件都是字符串格式。例如;条件((a和b)或(c和d))在"((a和b)或(c和d))"的后面。
基本上,我希望基于"or"操作符将单个复杂条件分解为多个更简单的条件。
任何帮助都将不胜感激。

ajsxfq5m

ajsxfq5m1#

function convertConditions(conditions) {
  const result = [];
  for (const condition of conditions) {
    let newCondition = condition.condition;
    // Replace "&&" with "," to split into multiple conditions
    newCondition = newCondition.replace(/&&/g, ',');
    // Split on "||" and flatten the resulting array
    const subConditions = newCondition.split('||').flat();
    for (const subCondition of subConditions) {
      result.push({
        condition: subCondition,
        result: condition.result
      });
    }
  }
  return result;
}

然后,您可以按如下方式使用此函数:

const input = [
  { condition: '((a && b) || (c && d))', result: 'Result A' },
  { condition: '(a || b || c) && ( d && e) && (x || y)', result: 'Result B' }
];
const output = convertConditions(input);
console.log(output);

这将输出以下数组:

[
  { condition: 'a && b', result: 'Result A' },
  { condition: 'c && d', result: 'Result A' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' }
]

相关问题