我有一个n个单词的数组作为字符串,如:
input: ["just", "a", "test"]
我需要做的是创建由空格分隔的这些单词的所有可能组合以及与原始字符串的组合.例如,上面应该创建:
output: [["just", "a", "test"], ["just a", "test"], ["just a test"], ["just", "a test"]]
我一直在使用itertools,但无法让它做我需要的.我现在所拥有的:
iterable = ['just', 'a', 'test']
for n in chain.from_iterable(combinations(iterable, n) for n in range(len(iterable)+1)):
print(n)
以下几乎按要求工作:
iterable = ['just', 'a', 'test']
L = [''.join(reversed(x)).rstrip()
for x in product(*[(c, c+' ') for c in reversed(iterable)])]
print(L)
谢谢.
编辑:
为了澄清这应该如何适用于长度为4的数组:
输入:[‘an’,’even’,’greater’,’test’]`
output:
['an', 'even', 'bigger', 'test']
['an even', 'bigger', 'test']
['an even bigger', 'test']
['an even bigger test']
['an', 'even bigger', 'test']
['an even', 'bigger test']
['an', 'even bigger test']
['an', 'even', 'bigger test']
解决方法:
这是一个解决方案.分区功能是courtesy of @Kiwi.
from itertools import combinations
iterable = ['just', 'a', 'test', 'and', 'another']
n = len(iterable)
def partitions(items, k):
def split(indices):
i=0
for j in indices:
yield items[i:j]
i = j
yield items[i:]
for indices in combinations(range(1, len(items)), k-1):
yield list(split(indices))
for i in range(1, n+1):
for x in partitions(iterable, i):
print([' '.join(y) for y in x])
['just a test and another']
['just', 'a test and another']
['just a', 'test and another']
['just a test', 'and another']
['just a test and', 'another']
['just', 'a', 'test and another']
['just', 'a test', 'and another']
['just', 'a test and', 'another']
['just a', 'test', 'and another']
['just a', 'test and', 'another']
['just a test', 'and', 'another']
['just', 'a', 'test', 'and another']
['just', 'a', 'test and', 'another']
['just', 'a test', 'and', 'another']
['just a', 'test', 'and', 'another']
['just', 'a', 'test', 'and', 'another']