首页 > 解决方案 > 如何使用多个条件搜索列表并获得最佳匹配?

问题描述

在搜索列表时,我试图根据多个条件获得最佳匹配。这些列表的长度可能相同,也可能不同:

list1 = [10,20,30,40,50,60,70,80]
list2 = [10,15,20,25,30,35]
list3 = [10,12,15,18,20,30,40]

search_criteria = [10,20] # should return all three lists

search_criteria2 = [10,15,20,25] # should return list2 first and list 3 as a close match

search_criteria3 = [35] # only returns list 2

search_criteria4 = [10,80,100] # returns list1 as best match

我曾想过使用列表推导:

listmatch = [i for i in search_criteria3 if i in list2]
if listmatch:
    print("list 2 matches")

或者

if listmatch:
    print("list 2 is the best choice")
else: print("no matches")

并重复列表。我正在尝试找到一种方法来获得最接近的匹配/最佳匹配。

编辑:目前将最佳匹配定义为仅匹配的标准数量。

标签: pythonlist

解决方案


您可以创建一个函数,计算列表的相似度得分,并返回最高的相似度得分。

def check(target, given_lists):
    max_score, ans = 0,0
    for num, given in enumerate(given_lists):
        score = 0
        for i in given:
            if i in target:
                score += 1
        if score>max_score:
            ans = num
    return num+1   #number of the current list

l1 = [...]
l2 = [...]
l3 = [...]
target_list = [...]
print(check(target_list, [l1,l2,l3]))

推荐阅读