如何使用多个条件搜索列表并获得最佳匹配?

2024-10-06 11:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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")

并在列表中重复。我正试图找到一种方法来获得最接近的比赛/最好的比赛

编辑:将当前最佳匹配定义为仅匹配的条件数


Tags: 列表searchreturnifasmatch条件list
2条回答

您可以创建一个函数,用于计算列表的相似性分数,并返回最高的相似性分数

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]))
sum([i==j for j in list3 for i in search_criteria2]) 

你可以使用上面的函数得到匹配值,然后根据

相关问题 更多 >