python - python中列表的详尽组合

标签 python combinations nested-lists python-itertools

我有一长串 Python 列表,看起来像这样:

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])

]

而且我想详尽列举共同值(value)观

('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]),

同样适用于四人、五人、六人一组,直到所有公共(public)值都被识别(假设列表更长)

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

我一直在尝试编写一个函数,为我生成的每个新列表循环遍历原始列表,但进展并不顺利!

这是我的:

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 一起使用

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

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 - python中列表的详尽组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19810946/

相关文章:

javascript - 密码锁游戏 (JavaScript)

python - 对多值字典的嵌套列表中的所有值运行查询

C# list of lists - 如何使列表中的列表具有唯一性和抗版本性?

python - 为什么此链接列表代码在 HackerRank 中显示错误?

java - 如何对字符串的所有可能组合进行编码?

C - 整数之间 2 个变量的组合 [ARRAY]

python - 返回嵌套列表中的项目(python)

python - 我将如何标准化 csv 文件中的日期? Python

python - 函数 python 调用后未返回内存

python - 按最接近字段的日期对 Mongodb 查询中的文档进行排序