python - 获取python中大多数列表的公共(public)元素

标签 python

给定 4 个列表,我想获取 3 个或更多列表共有的元素。

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
c = [1, 3, 4, 5, 6]
d = [1, 2, 6, 7]

因此,输出应该是[1, 2, 3, 4]

我目前的代码如下。

result1 = set(a) & set(b) & set(c)
result2 = set(b) & set(c) & set(d)
result3 = set(c) & set(d) & set(a)
result4 = set(d) & set(a) & set(b)

final_result = list(result1)+list(result2)+list(result3)+list(result4)
print(set(final_result))

它工作正常,并提供所需的输出。但是,我很想知道在 Python 中是否有一种简单的方法可以做到这一点,即:是否有任何内置函数?

最佳答案

使用 Counter ,你可以这样做:

代码:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5]
c = [1, 3, 4, 5, 6]
d = [1, 2, 6, 7]

from collections import Counter

counts = Counter(sum(([list(set(i)) for i in (a, b, c, d)]), []))
print(counts)

more_than_three = [i for i, c in counts.items() if c >= 3]
print(more_than_three)

结果:

Counter({1: 4, 2: 3, 3: 3, 4: 3, 5: 2, 6: 2, 7: 1})

[1, 2, 3, 4]

关于python - 获取python中大多数列表的公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372753/

相关文章:

python - 即使连接关闭,Pandas read_sql_query 仍在后台运行?

python - 导入 CV2 时收到来自 lingnutls/'Hogweed' 的错误

python - pandas 从日期范围列中提取开始和结束日期

python - 在文件中查找字符串的最快方法

python - 使用部分关键字搜索 python dict 的最快方法

python - pygame不刷新屏幕

python - Django:在列表中查找不在数据库中的项目

python - 数据框中非数字和零值单元格的索引

python - Pandas read_csv 多个文件

java - TCP Socket 通信 Java - Python