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")
并重复列表。我正在尝试找到一种方法来获得最接近的匹配/最佳匹配。
编辑:目前将最佳匹配定义为仅匹配的标准数量。
解决方案
您可以创建一个函数,计算列表的相似度得分,并返回最高的相似度得分。
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]))
推荐阅读
- excel-formula - 仅突出显示相对值上方的 1 个单元格和下方的 1 个单元格
- asp.net-core - 如何使用 Identity 在 ApplicationDbContext 中获取当前登录的用户 ID?
- python - python中hashmap中的自动键分配
- kubernetes - Kubernetes 是否支持虚拟机/节点配置和管理?
- python - python - 是否可以映射数据并制作矢量矩阵?
- ios - 更改 CAShapeLayer 笔划位置
- asynchronous - Vertx 上下文和 Kotlin Couroutine 上下文之间的区别
- c# - 位图保存期间 GDI+ 中发生一般错误
- python - 读取 >2000 行文本文件,但它在第 46 行停止,即为空。为什么?
- google-maps-api-3 - 如何在 GMaps API v3 中拖动标记时防止地图平移