查找列表和列表元素之间的部分字符串匹配

时间:2020-05-15 03:13:45

标签: python-3.x

我有一个字符串列表:

mylist = ['foo hydro', 'bar']

和一个称为test的字符串列表:

testI = ['foo', 'bar']             ## should succeed
testJ = ['foo']                    ## should fail
testK = ['foo hydro']              ## should fail
testL = ['foo hydro', 'bar']       ## should succeed
testM = ['foo', 'bar', 'third']    ## should fail

test = [testI,testJ,testK,testL,testM]

我需要检查test中每个列表的每个元素和mylist中每个元素之间是否存在(部分或全部)字符串匹配。

因此,testI应该成功,因为testI[0]mylist[0] 的部分字符串匹配,而因为testI[1]是{的完整字符串匹配{1}}。

但是,mylist[1]testJ都应该失败,因为它们只匹配testK中两个字符串之一,而mylist应该失败,因为它们包含一个不包含元素的元素与testM

中的任何元素都不匹配

到目前为止,我已经尝试过使用mylist

any

因此,我可以捕获mylist中的任何元素是否与测试中每个列表中的任何元素匹配,但是我无法找到一种满足所有要求的方法。

有什么建议吗?我很高兴重构这个问题,以使其更容易处理。

2 个答案:

答案 0 :(得分:1)

我想为您的问题提供解决方案。

首先,我们创建一个函数来识别一个单词是否是另一个列表中任何单词的子字符串:

def is_substring_of_element_in_list(word, list_of_str):
    if len(list_of_str) == 0:
        return (False, -1)
    is_sub = any([word in s for s in list_of_str])
    if (is_sub == True):
        ix = [word in s for s in list_of_str].index(True)
    else: 
        ix = -1
    return is_sub, ix 

现在,我们可以使用此功能来检查测试列表中的每个单词是否是列表中单词的子字符串。请注意,每个单词只能使用一次,因此如果给定单词​​是该单词的子字符串,则需要删除一个字符串。

def is_list_is_in_mylist(t, mylist):
    mylist_now = sorted(mylist, key=len)
    test_now = sorted(t, key=len)
    counter = 0
    for word in t:
        is_sub, index = is_substring_of_element_in_list(word, mylist_now)
        if is_sub:
            mylist_now.pop(index)
            test_now.remove(word)
            counter += 1
    if counter == len(t) and counter == len(mylist):
        print("success")
    else:
        print("fail")

请注意,我们需要对列表中的元素进行排序,以避免单词顺序引起的错误。例如,如果my_list = ['f', 'foo']test1 = ['f', 'foo']test2 = ['foo', 'f']不进行排序,则成功之一将失败,另一个将失败。

现在,您可以使用简单的for循环遍历测试:

for t in test:
    is_list_is_in_mylist(t, mylist)

答案 1 :(得分:0)

我认为这段代码可能符合您的条件:

for t in test:
    counter = 0
    if len(t) == len(mylist):
        t = list(dict.fromkeys(t))
        temp = []
        for s in t:
            if not any([s in r for r in t if s != r]):
                temp.append(s)
        for l in temp:
            for m in mylist:
                if l in m:
                    counter = counter + 1
        if counter == len(mylist):
            print('successed')
        else:
            print('fail')
    else:
        print('fail')