【发布时间】:2015-10-13 09:47:55
【问题描述】:
我使用的是 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
但我希望输出仅是与stuff 列表顺序相同的组合。例如。删除 a d、b d、a b d 和 a c d,因为与 stuff 列表 ["a", "b", "c", "d"] 相比,它们的顺序不正确。
我已经想办法改用这个了:
import itertools
stuff = ["a","b","c", "d"]
for L in range(1, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
if ' '.join(subset) in ' '.join(stuff): #added line
print( ' '.join(subset))
正在给我想要的输出:
a
b
c
d
a b
b c
c d
a b c
b c d
a b c d
但是 Python 中是否有任何内置方法可以满足我的需求?
【问题讨论】:
-
为什么
a d的顺序不正确?你是什么意思订单?您是否只对原始列表的 slices 感兴趣?为什么a c的顺序不正确而a d不正确?
标签: python list combinations itertools