查找严格在X个列表中的N个元素 [英] Finding elements that are in strictly N of X lists

查看:57
本文介绍了查找严格在X个列表中的N个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有N个列表,并且想知道哪些元素严格存在于这些列表中的X个中.我了解,如果我有两个列表,那就很简单了:

I have N lists, and would like to know which elements are present in strictly X of those lists. I understand that if I have two lists, it's rather straightforward:

lst_a = [1,2,3]
lst_b = [1,2,5]

overlap = list(set(a) & set(b))

如果我有5个列表,并且想知道严格来说其中有4个元素,该怎么办?

What if I have, say, 5 lists, and want to know which elements are in strictly 4 of those?

推荐答案

使用计数器合并:

from collections import Counter

lst_a = [1,2,3]
lst_b = [1,2,5]
lsts = [lst_a, lst_b]

counter = Counter()
for lst in lsts:
    unique = set(lst)
    counter += Counter(unique)

n = 2
print(f"elements in exactly {n} lsts:")
for k, v in counter.items():
    if v == n:
        print(k)

这篇关于查找严格在X个列表中的N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆