Python:生成列表的所有有序组合

Python:生成列表的所有有序组合,python,list,combinations,itertools,Python,List,Combinations,Itertools,我正在使用Python 2.7 我有一个列表,我想要所有可能的有序组合 import itertools stuff = ["a","b","c", "d"] for L in range(1, len(stuff)+1): for subset in itertools.combinations(stuff, L): print( ' '.join(subset)) 这将产生以下输出: a b c d a b a c <-- not in correct ord

我正在使用Python 2.7

我有一个列表,我想要所有可能的有序组合

import itertools
stuff = ["a","b","c", "d"]
for L in range(1, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print( ' '.join(subset))
这将产生以下输出:

a
b
c
d
a b
a c <-- not in correct order
a d <-- not in correct order
b c
b d <-- not in correct order
c d
a b c
a b d <-- not in correct order
a c d <-- not in correct order
b c d
a b c d
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['c']
['c', 'd']
['d']
正在给我想要的输出:

a
b
c
d
a b
b c
c d
a b c
b c d
a b c d

但是Python中有没有什么内置方法可以满足我的要求呢?

我想你的意思是“以正确的顺序”以连续的顺序,在这种情况下,你只需要使用两个指针来迭代
东西

stuff = ["a","b","c", "d"]
# sort stuff here if it's not sorted

result = []
for i in xrange(len(stuff)):
    for j in xrange(i+1, len(stuff)+1):
        result.append(stuff[i:j])

# sort the result by length, maybe you don't need it
result = sorted(result, key=len)

for r in result:
    print ' '.join(r)

我相信你正在寻找的都是你原来清单中可能的部分。您希望转换为切片的输出如下所示:

a         # slices[0:1]
b         # slices[1:2]
c         # slices[2:3]
d         # slices[3:4]
a b       # slices[0:2]
b c       # slices[1:3]
c d       # slices[2:4]
a b c     # slices[0:3]
b c d     # slices[1:4]
a b c d   # slices[0:4]
因此,您应该尝试生成这些索引。如果你仔细观察并对它们进行排序,你会发现这些是0到4之间的2个数字组合,其中第一个数字比另一个小,这正是
itertools.compositions
对索引列表所做的。因此,我们可以生成这些:

for i, j in itertools.combinations(range(len(stuff) + 1), 2):
    print(stuff[i:j])
这将产生以下输出:

a
b
c
d
a b
a c <-- not in correct order
a d <-- not in correct order
b c
b d <-- not in correct order
c d
a b c
a b d <-- not in correct order
a c d <-- not in correct order
b c d
a b c d
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['c']
['c', 'd']
['d']
这样做的好处是,它会生成您输入的实际子列表,并且不关心这些子列表是否首先包含单个字符。它可以是列表中的任何类型的内容

如果输出顺序非常重要,则可以按输出列表大小排序以获得所需结果:

def getCombinations (lst):
    for i, j in itertools.combinations(range(len(lst) + 1), 2):
        yield lst[i:j]

for x in sorted(getCombinations(stuff), key=len):
    print(' '.join(x))

为什么
ad
的顺序不正确?什么叫订单?您是否只对原始列表中的部分感兴趣?为什么
a c
的顺序正确,而
a d
的顺序不正确?你可以用
key=lambda x:len(x)
替换为just
key=len
@TigerhawkT3是的,它更优雅。我想你说的“顺序正确”是指连续顺序。感谢您的回复:)优雅的代码。也许最终结果需要排序,就像示例输出一样。@WKPlus这是一个很好的观点,添加了一种方法。谢谢!:)如果您使用
itertools.compositions
而不是
itertools.permutations
,如果i行,您可以省略
。@WKPlus哦,您是对的。我以前测试过它,但当时没有
len+1
部件,因此无法工作。我想我以后没有再测试它了……再次感谢!:)