我有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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句