根据百分比从列表中提取元素

时间:2017-04-06 05:29:01

标签: python list

说我有一个n个子列表的列表,

a =[["cat", "dog", "cow", "apple"], ["apple", "dog"],  ["cat", "apple"]["cat","apple", "deer"]]

假设阈值百分比为70%,则子列表中至少70%的时间出现的元素应该在输出中。 在这个例子中," apple"出现在所有子列表中," cat"在所有子列表中有3/4时间。 因此,输出应该是[" apple"," cat"] 我怎样才能做到这一点?

我正在使用交集,但是只有所有子列表中的公共元素才会出现在输出中。

output= list(set(a[0]).intersection(*a))

2 个答案:

答案 0 :(得分:3)

您可以使用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']

答案 1 :(得分:2)

这将完成这项工作:

import collections
import itertools
a =[["cat", "dog", "cow", "apple"], ["apple", "dog"],  ["cat", "apple"],["cat","apple", "deer"]]
n=len(a)
counter = collections.Counter(itertools.chain(*a))
res=[i for i in counter if counter[i]>=0.7*n]
print(res)

打印

['cat', 'apple']
相关问题