【发布时间】:2015-10-02 02:54:29
【问题描述】:
我有一个列表 ['a', 'b', 'c', 'd'] 我需要一个列表 ['a', 'ab', 'abc', 'abcd', 'b '、'bc'、'bcd'、'c'、'cd'、'd']。
我一直在查看itertools,但我不知道如何使这项工作发挥作用。
对于all combinations,代码为:
from itertools import permutations
stuff = ['a','b','c','d']
for i in range(0, len(stuff)+1):
for subset in permutations(stuff, i):
print(subset)
我需要做什么才能只返回顺序组合?我想我可以随时检查每个排列的顺序,但这似乎不是最好的方法。
【问题讨论】:
-
你还需要
'abc'和'd'吗?因为否则我在您的列表中看不到任何逻辑。 -
'abc'是否也应该在您要构建的列表中? -
类似
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)]) -
您想要组合,而不是排列,或者更确切地说是“有序”组合。见 itertools.combinations
-
我撒谎了,组合就像 [('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c ', 'd'), ('b', 'c', 'd')]