python - 比较列表并查找组合
问题描述
我有 3 个列表,我正在尝试找到匹配的组合。
mylist1 = ["a", "b", "c", "d", "e", "f", "x", "y", "p"]
mylist2 = ["a", "b", "c", "d", "p", "q"]
mylist3 = ["a", "b", "c", "d", "e", "f", "g", "h", "q"]
g、h、x 和 y 没有任何匹配项,所以我将丢弃它们。结果 ["a", "b", "c" ] 3 是有效的,但我也需要丢弃它,因为这是 ["a", "b", "c", "d"] 3 的子集预期的输出是:
["a", "b", "c", "d"] 3
["a", "b", "c", "d", "e", "f"] 2
["a", "b", "c", "d", "p"] 2
["a", "b", "c", "d", "q"] 2
解决方案
假设您的要求是:您不想看到仅出现一次的任何内容 - 但只想显示至少在您的两个列表中常见的任何内容。
首先,您需要弄清楚可以从列表中选择多少种组合。在这里,您有 3 个列表-> 即 4 种组合-itertools.combinations
可以提供帮助
然后,您需要定义组合并将它们一一相交,如下所示:
import itertools
from functools import reduce
mylist1 = ["a", "b", "c", "d", "e", "f", "x", "y", "p"]
mylist2 = ["a", "b", "c", "d", "p", "q"]
mylist3 = ["a", "b", "c", "d", "e", "f", "g", "h", "q"]
def definer(*args):
# Number of lists for input
counter = len(args)
my_outputs = []
# Only collecting where values are at least in two lists:
for i in range(2, counter+1):
x = (g for g in itertools.combinations(args, i))
for item in x:
result = reduce(set.intersection, (set(a) for a in item))
my_outputs.append([sorted(list(result)), i])
return my_outputs
print(definer(mylist1,mylist2,mylist3))
推荐阅读
- excel - 与属于列表的标准相对应的数字的 sumproduct
- javascript - 使用 SelectBoxIt js 时,JAWS 不读取使用无序列表创建的下拉列表项
- javascript - 为迷你播放器功能禁用 YouTube 的下拉功能
- angular - 子组件的唯一提供者值
- python - 如何在 Python for Leaflet 中将地球图像调整为平坦?
- google-sheets - 基于具有日期范围+单个日期的单个单元格条件格式化多个单元格
- java - Bukkit 自定义死亡系统
- cassandra - 一致性 ONE/LOCAL_QUORUM 读取查询期间的 Cassandra 超时
- c# - 当我从不使用 Invoke 或 BeginInvoke 时,不能调用 Invoke 或 BeginInvoke 错误
- jquery - 如何计算一个类别和作者的帖子数量