我有一个字符串列表:
l = ['a', 'b', 'c']
我想在不同大小的组中创建列表元素的所有可能组合。我希望这是元组的元组的列表,但它也可以是列表的列表的列表等。元组的顺序以及元组中元组的顺序并不重要。列表元素不能在元组或元组的元组中重复。对于上面的列表,我期望类似的内容:
[(('a'),('b'),('c')),
(('a', 'b'), ('c')),
(('a', 'c'), ('b')),
(('b', 'c'), ('a')),
(('a', 'b', 'c'))]
非常感谢任何帮助。
编辑: 我确实要求列表中的每个元组都包含 l 的所有元素。 senderle 和 Antimony,你们对于遗漏的看法都是正确的。
最佳答案
这是一种做事的方法。不知道还有没有更优雅的方法。 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
关于Python-将列表组合排列成各种大小的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850950/