python中列表的详尽组合 [英] Exhaustive combinations of lists in python

查看:93
本文介绍了python中列表的详尽组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有很长的列表,看起来像这样:

I have a long list of lists in Python that looks something like this:

myList=[

('a',[1,2,3,4,5]),
('b',[6,7,8,9,10]),
('c',[1,3,5,7,9]),
('d',[2,4,6,8,10]),
('e',[4,5,6,7,8])

]

我想详尽地列举出共同的价值观

And I would like to enumerate the common values exhaustively

('a:b', ),
('a:c', [1,3,5]),
('a:d', [2,4]),
('a:e', [4,5]),
('b:c', [7,9]),
('b:d', [6,8,10]),

('a:c:e', [5]),
('b:c:e', [7]),
('b:d:e', [6,8]),

在四个,五个,六个组中也是如此,直到所有通用值都被确定(假设列表更长)

and the same for groups of four, five, six until all common values have been identified (assuming the lists were longer)

是否可以使用itertools库或上述集合或组合?

Is this possible using the itertools library or sets or a combination of the above?

我一直在尝试为我生成的每个新列表编写一个遍历原始列表的函数,但是运行不顺利!

I have been trying to write a function that loops over the original list for every new list I generate but It hasn't been going well!

这就是我所拥有的:

def findCommonElements(MyList):

    def sets(items):
        for name, tuple in items:
            yield name, set(tuple)

    def matches(sets):
       for a, b in combinations(sets, 2):
           yield ':'.join([a[0], b[0]]), a[1] & b[1]

    combinationsSet=list(matches(sets(keywordCount)))

    combinationsList=[]
    for pair,tup in combinationsSet:
        setList=list(tup)
        combinationsList.append((pair, len(setList), setList))
    combinationsList=sorted(combinationsList,key=lambda x: x[1], reverse=True) #this just sorts the list by the number of common elements

    return combinationsList

推荐答案

我认为您可以尝试将itertools.combinationsitertools.chain

I think You can try to use itertools.combinations with itertools.chain

一个很好的例子,但它应该可以工作. 我将在这里使用itertools和生成器:

nit very good example but It should work. I will use itertools and generators here:

lengthes = xrange(2, len(myList)+1)
combinations_list = (itertools.combinations(myList, i) for i in lengthes)
combinations = itertools.chain.from_iterable(combinations_list)
def find_intersection(lists):
    res = set(lists[0])
    for data in lists:
        res &= set(data)
    return res
result = [(':'.join(i), list(find_intersection(v))) for i, v in (zip(*x) for x in combinations)]

或仅itertools.combinations

def findCommonElements(MyList):

    combinationsList=[]

    for seq_len in xrange(2, len(MyList)+1):
        for combination in combinations:
            for indexes, values in zip(*combination):
                intersection = reduce(lambda x, y: x & set(y[1]), 
                                      values, set(values[0]))
                if intersection:
                    combinationsList.appen(':'.join(indexes), intersection)
        return combinationsList

这篇关于python中列表的详尽组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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