我有一套清单:
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]
答案 0 :(得分:1)
from collections import Counter
a = [{'foo','cpu','phone'},{'foo','mouse'}, {'dog','cat'}, {'cpu'}]
x = Counter(sum([list(i) for i in a], []))
z = [a for a, b in dict(x).items() if b >=2]
res = []
for i in a:
for j in i:
if j in z:
res.append(i)
break
print(res)
输出
[{'foo', 'phone', 'cpu'}, {'foo', 'mouse'}, {'cpu'}]
答案 1 :(得分:1)
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)