📜  Python|列表的相似度百分比

📅  最后修改于: 2022-05-13 01:55:49.881000             🧑  作者: Mango

Python|列表的相似度百分比

有时,在使用Python列表时,我们会遇到一个问题,即我们需要找出一个列表与其他列表的相似程度。这两个列表的相似商是我们可能遇到的许多场景所需要的。让我们讨论一种可以执行此任务的方式。

方法:使用"|" operator + "&" operator + set()
正式应用于计算列表之间相似性的方法是找到不同的元素和共同的元素并计算它的商。然后将结果乘以 100,得到百分比。

# Python3 code to demonstrate working of
# Percentage similarity of lists
# using "|" operator + "&" operator + set()
  
# initialize lists
test_list1 = [1, 4, 6, 8, 9, 10, 7]
test_list2 = [7, 11, 12, 8, 9]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Percentage similarity of lists
# using "|" operator + "&" operator + set()
res = len(set(test_list1) & set(test_list2)) / float(len(set(test_list1) | set(test_list2))) * 100
  
# printing result
print("Percentage similarity among lists is : " + str(res))
输出 :
The original list 1 is : [1, 4, 6, 8, 9, 10, 7]
The original list 2 is : [7, 11, 12, 8, 9]
Percentage similarity among lists is : 33.33333333333333