首页 > 解决方案 > 比较列表并查找组合

问题描述

我有 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

标签: python

解决方案


假设您的要求是:您不想看到仅出现一次的任何内容 - 但只想显示至少在您的两个列表中常见的任何内容。

首先,您需要弄清楚可以从列表中选择多少种组合。在这里,您有 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))

推荐阅读