假设我有一个包含 n 个子列表的列表,
a =[["cat", "dog", "cow", "apple"], ["apple", "dog"], ["cat", "apple"]["cat","apple", "deer"]]
假设阈值百分比为 70%,在子列表中出现至少 70% 的时间的元素应该在输出中。 在此示例中,“apple”出现在所有子列表中,“cat”出现在所有子列表中的 3/4 次。 因此,输出应该是 ["apple", "cat"] 我怎样才能做到这一点?
我使用的是交集,但只有所有子列表中的公共(public)元素才会出现在输出中。
output= list(set(a[0]).intersection(*a))
请您参考如下方法:
你可以使用Counter
>>> from collections import Counter
>>> c = Counter()
>>> for l in a:
... c.update(set(l))
...
>>> c
Counter({'apple': 4, 'cat': 3, 'dog': 2, 'deer': 1, 'cow': 1})
>>> [key for key, value in c.items() if value >= 0.7 * len(a)]
['cat', 'apple']
