这更像是一个数学问题而不是其他什么。假设我在Python中有两个大小不同的列表。
listA = ["Alice", "Bob", "Joe"]
listB = ["Joe", "Bob", "Alice", "Ken"]
我想找出这两个列表重叠的百分比。列表内部顺序不重要。找出重叠的部分很容易,我已经看到其他帖子上如何做到这一点,但是我无法将其扩展到找出重叠的百分比上。如果我以不同的顺序比较列表,结果会有所不同吗?最好的方法是什么?
这更像是一个数学问题而不是其他什么。假设我在Python中有两个大小不同的列表。
listA = ["Alice", "Bob", "Joe"]
listB = ["Joe", "Bob", "Alice", "Ken"]
我想找出这两个列表重叠的百分比。列表内部顺序不重要。找出重叠的部分很容易,我已经看到其他帖子上如何做到这一点,但是我无法将其扩展到找出重叠的百分比上。如果我以不同的顺序比较列表,结果会有所不同吗?最好的方法是什么?
从校长的角度来看,我认为你可能会问两个明智的问题:
当然也可以找到其他含义,而且可能有很多。总之,你应该知道自己要解决的问题。
从编程角度来看,解决方案很容易:
listA = ["Alice", "Bob", "Joe"]
listB = ["Joe", "Bob", "Alice", "Ken"]
setA = set(listA)
setB = set(listB)
overlap = setA & setB
universe = setA | setB
result1 = float(len(overlap)) / len(setA) * 100
result2 = float(len(overlap)) / len(setB) * 100
result3 = float(len(overlap)) / len(universe) * 100
>>> len(set(listA)&set(listB)) / float(len(set(listA) | set(listB))) * 100
75.0
len(set(listA)&set(listB))
返回常见项(在您的示例中为3)。
len(set(listA) | set(listB))
返回总不同项目的数量(4)。当两个列表具有完全不同的元素时,最大差异就会出现。因此,我们最多有n + m
个离散元素,其中n
是第一个列表的大小,m
是第二个列表的大小。一种度量方法可以是:
2 * c / (n + m)
其中c
是共同元素的数量。可以按以下百分比计算:
200.0 * len(set(listA) & set(listB)) / (len(listA) + len(listB))
def computeOverlap(L1, L2):
d1, d2 = {}, {}
for e in L1:
if e not in d1:
d1[e] = 1
d1[e] += 1
for e in L2:
if e not in d2:
d2[e] = 0
d2[e] += 1
o1, o2 = 0, 0
for k in d1:
o1 += min(d1[k], d2.get(k,0))
for k in d2:
o2 += min(d1.get(k,0), d2[k])
print((100*o1) if o1 else 0 "% of the first list overlaps with the second list")
print((100*o2) if o2 else 0 "% of the second list overlaps with the first list")
from collections import defaultdict, Counter
def computeOverlap(L1, L2):
d1 = defaultdict(int, Counter(L1))
d2 = defaultdict(int, Counter(L2))
o1, o2 = 0, 0
for k in d1:
o1 += min(d1[k], d2[k])
for k in d2:
o2 += min(d1[k,0], d2[k])
print((100*o1) if o1 else 0 "% of the first list overlaps with the second list")
print((100*o2) if o2 else 0 "% of the second list overlaps with the first list")
2*匹配数/(lista长度+len(listb)长度)
或其他。 - ZdaR[1,1,1]
和[1]
,重叠部分是100%还是33%? - tobias_kset()
非常有用),还是包括重复元素在内的所有元素的百分比? - pcurry