我正在开发一个项目,我必须将一个列表(实际)与另一个列表(预期)进行比较。 预期列表是固定的,但实际列表有时可能有“附加元素”或“拼写错误”或两者都有。下面的例子两者都有。
预期列表:(长度 = 14)
exp = ['表格变更','死亡证明','授权表格', '付款表格','提交表格','证明文件', '权威证明','执行人证明','身份证明', '反向表格','法定声明','协议', ‘转移’、‘调解员’]
实际列表:(长度 = 15)
act = ['形式变更','死亡证明', '授权表格','付款表格','提交表格','证明文件', '授权证明','执行人证明','身份证明','所有权证明', '反向形式','法定声明','协议','转让','调解员'] # length = 15
现在我的逻辑如下,
import itertools
temp_new = []
if len(exp) < len(act):
# extend the expected list
exp = exp[:len(act)] + ['']*(len(act) - len(exp))
# creating new list
for e,a in itertools.zip_longest(range(len(exp)),range(len(act))):
temp_new += ['missing']
if (act[a] in exp) or ( set(act[a].split()) & set(exp[e].split()) ):
temp_new[a] = act[a]
给我以下输出:
temp_new = ['形式变更','死亡证明', '授权表格','付款表格','提交表格','证明文件', '权威证明','执行人证明','身份证明','失踪', ‘反向表格’、‘法定声明’、‘协议’、‘转让’、‘调解员’]
我实际上正在寻找的是以下列表,
expected_output = ['形式变更','死亡证明', '授权表格','付款表格','提交表格','证明文件', '权威证明','执行人证明','身份证明','失踪', '反向表格'、'法定声明'、'协议'、'转让'、'调解员']'
有人可以帮我纠正我当前的逻辑或为我提供一个新的逻辑吗?
提前非常感谢您!
这可能就像附加
exp[a]
而不是 act[e]
一样简单。这将添加“证书”而不是“证书”。
通过使用
in
关键字,每次通过 actual
也是一次通过 expected
。您也可以显式地使用嵌套循环。
def compare_lists(exp, act):
temp_new = []
range_start = 0 # ensure that elements in lists are in order
for a in act:
append_val = 'missing'
for exp_idx in range(range_start, len(exp)):
a = exp[exp_idx]
if (e == a) or _string_partial_match(e, a):
append_val = e
range_start = range_start + 1
break
temp_new.append(append_val)
return temp_new
def _string_partial_match(e:str, a:str):
# return set(a.split()) & set(e.split())
return any([(ew == aw) for ew, aw in zip(e.split(), a.split())])
该函数返回:
['change of form', 'death certificate', 'authority form', 'payment form', 'lodgement form', 'supporting documentation', 'proof of authority', 'proof of executor', 'proof of identity', 'missing', 'reverse form', 'statutory declaration', 'agreements', 'transfers', 'mediators']
如果实际列表中的值与预期列表中较早的值匹配是可以的,那么您可以取消
range_start
变量,只写 for e in exp:
。