检查一对字符串是否是压缩列表的子字符串 - python

时间:2018-05-31 00:16:10

标签: python python-3.x python-2.7 zip substring

b_list=["some data"]
s_list=["some data"]

approved_b=[list of "b_list" elements that are approved]
approved_s=[list of "s_list" elements that are approved]

br, sr=[],[]
for b,s in zip(b_list, s_list):
    if (b,s) in zip(approved_b, approved_s):
        br.append(b)
        sr.append(s)

问题在于:

如果你有alpha,则需要认识到alpha相当于alpha 1alpha 100zoom alpha等。这可以通过x in y。 但是,我需要能够同时(一次两次)完成整个拉链。

示例:

b_list=['alpha', 'beta time', 'gamma', 'ohm']
s_list=['gary', 'paul', 'lime', 'apple']

approved_b=['alpha 1', 'beta', 'gamma 2', 'ohm']
approved_s=['gary time', 'zoom', 'lime time', 'appler']

结果必须是:

br=['alpha','gamma']
sr=['gary','lime']

基本上,当它进行验证时,需要检查(b,s)中的(b_list, s_list)对是否与(approved_b,approved_s)匹配,b可以是approved_b的子字符串,而approved_b可以是b 同一时间的子字符串s可以是approved_s的子字符串, approved_s可以是s的子字符串。

1 个答案:

答案 0 :(得分:1)

我不得不从你的代码中承担很多,因为我不太关注你的描述。听起来您只想匹配approved列表中的整个单词,因此您可以在每个条目的in上使用split(),例如:

def match_pair(e1, e2, lst1, lst2):
    return any(e1 in l1.split() and e2 in l2.split() for l1, l2 in zip(lst1, lst2))

In []:
br, sr = zip(*[(b, s) for b, s in zip(b_list, s_list) 
               if match_pair(b, s, approved_b, approved_s)])
print(br)

Out[]:
('alpha', 'gamma')

In []:
print(sr)

Out[]:
('gary', 'lime')

从长远来看,这将是:

br, sr = [], []
for b, s in zip(b_list, s_list):
    if match_pair(b, s, approved_b, approved_s):
        br.append(b)
        sr.append(s)

希望这有帮助。