Python 通过集合列表筛选出现次数
我有一个集合列表:Python 通过集合列表筛选出现次数,python,list,set,Python,List,Set,我有一个集合列表: a = [{'foo','cpu','phone'},{'foo','mouse'}, {'dog','cat'}, {'cpu'}] 预期成果: 我想查看每个字符串,进行计数并以原始格式返回所有x>=2: a = [{'foo','cpu','phone'}, {'foo','mouse'}, {'cpu'}] 我尝试使用列表理解循环,但它不适用于集合列表: a = [k for k in a if a.count(k) >= 2] 输出 [{'foo', 'p
a = [{'foo','cpu','phone'},{'foo','mouse'}, {'dog','cat'}, {'cpu'}]
预期成果:
我想查看每个字符串,进行计数并以原始格式返回所有x>=2
:
a = [{'foo','cpu','phone'}, {'foo','mouse'}, {'cpu'}]
我尝试使用列表理解循环,但它不适用于集合列表:
a = [k for k in a if a.count(k) >= 2]
输出
[{'foo', 'phone', 'cpu'}, {'foo', 'mouse'}, {'cpu'}]
再说一遍,规则是什么?为什么预期输出中有
phone
,'foo'和'cpu'出现了2次,因此返回的整个集合
与=
不一样,a.count(k)
正在寻找与k
完全相同的值。因此,如果列表是[{'foo','cpu','phone'},{'foo','cpu'},{'dog','cat'},{'foo','cpu','phone'}]
,您的结果将是[{'foo','cpu','phone'},{'foo','cpu','phone'}
鼠标
只出现一次,为什么它会返回到所需的输出中?如果集合中的任何元素在任何集合中出现2次或2次以上,则整个集合应在输出中?
[{'foo', 'phone', 'cpu'}, {'foo', 'mouse'}, {'cpu'}]
from collections import Counter
counter = Counter()
for a_set in a:
# First we create a counter with counts for all words
counter.update(a_set)
result = []
for a_set in a:
for word in a_set:
if counter[word] >= 2:
# If any word in any set has a count of 2 or more we append the set
result.append(a_set)
break
print(result)