Python - 将列表组合排列到各种大小的元组列表中

时间:2012-10-12 01:19:50

标签: python list recursion tuples combinations

我有一个字符串列表:

l = ['a', 'b', 'c']

我想在不同大小的组中创建列表元素的所有可能组合。我希望这是一个元组元组的列表,但它也可以是列表列表等列表。元组的顺序和元组中的元组无关紧要。在元组的元组或元组中都不能重复列表元素。对于上面的列表,我希望如下:

[(('a'),('b'),('c')),
 (('a', 'b'), ('c')),
 (('a', 'c'), ('b')),
 (('b', 'c'), ('a')),
 (('a', 'b', 'c'))]

非常感谢任何帮助。

编辑: 我确实要求列表中的每个元组都包含l的所有元素。 sentle和锑,你对这些遗漏都是正确的。

2 个答案:

答案 0 :(得分:3)

这是一种做事的方法。我不知道是否有更优雅的方法。 itertools模块具有组合和排列的功能,但遗憾的是,没有用于分区的功能。

编辑:我的第一个版本不正确,但幸运的是,我已经从我做过的旧项目中解决了这个问题。

您还可以通过返回d而不是d.values()来获取表示与每个分区关联的边缘位集的唯一整数键。这对于有效地测试一个分区是否是另一个分区的细化非常有用。

def connectivityDictSub(num, d, setl, key, i):
    if i >= num:
        assert(key not in d)
        d[key] = setl
    else:
        for ni in range(len(setl)):
            nsetl, nkey = setl[:], key
            for other in nsetl[ni]:
                assert(other != i)
                x,y = sorted((i, other))
                ki = ((2*num-3-x)*x)/2 + y-1
                nkey |= 1<<ki
            nsetl[ni] = nsetl[ni] + [i] #not the same as += since it makes a copy
            connectivityDictSub(num, d, nsetl, nkey, i+1)
        nsetl = setl + [[i]]
        connectivityDictSub(num, d, nsetl, key, i+1)

def connectivityDict(groundSet):
    gset = sorted(set(groundSet))
    d = {}
    connectivityDictSub(len(gset), d, [], 0, 0)
    for setl in d.values():
        setl[:] = [tuple(gset[i] for i in x) for x in setl]
    return map(tuple, d.values())

for x in connectivityDict('ABCD'):
    print x

答案 1 :(得分:2)

itertools应该完成你想要的大部分工作。

示例:

stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
  for subset in itertools.combinations(stuff, L):
    print(subset)

该示例仅用于显示itertools。你必须弄明白才能得到你想要的确切输出。