gpt4 book ai didi

python - 通过集合列表过滤出现次数

转载 作者:行者123 更新时间:2023-12-01 00:35:15 25 4
gpt4 key购买 nike

我有一个集合列表:

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]

最佳答案

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)

关于python - 通过集合列表过滤出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com