I have list of dict
s:
print (L)
[{0: 'x==1', 1: 'y==2', 2: 'z!=1'}, {0: 'x==1', 1: 'y<=3', 2: 'z>1'}]
我想创建元组,其值位于运算符之前、运算符之后、值之后:
#first step
wanted = [[('x', '==', '1'), ('y', '==', '2'), ('z', '!=', '1')],
[('x', '==', '1'), ('y', '<=', '3'), ('z', '>', '1')]]
然后通过运算符映射第二个值:
import operator
ops = {'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'==': operator.eq,
'!=': operator.ne}
#expected final output
wanted = [[('x', <built-in function eq>, '1'),
('y', <built-in function eq>, '2'),
('z', <built-in function ne>, '1')],
[('x', <built-in function eq>, '1'),
('y', <built-in function le>, '3'),
('z', <built-in function gt>, '1')]]
I try:
L = [[re.findall(r'(.*)([<>=!]+)(.*)', v)[0] for k, v in x.items()] for x in L]
print (L)
[[('x=', '=', '1'), ('y=', '=', '2'), ('z!', '=', '1')],
[('x=', '=', '1'), ('y<', '=', '3'), ('z', '>', '1')]]
L = [[ops[y[1]] for y in x] for x in L]
但问题是错误匹配中间子串 - 运算符,然后错误匹配运算符值。
正确匹配的正确正则表达式是什么?或者这是其他一些可能的解决方案。例如经过string.partition
?我开放所有可能的解决方案。