Python:生成多个带空格的字符串组合

标签 python string combinations whitespace permutation

我有一个包含 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', 'bigger', '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']

最佳答案

这是一个解决方案。 partitions 函数是 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']        

关于Python:生成多个带空格的字符串组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50005856/

相关文章:

python - 合并多个字典列表,添加重复项的值并排序

c - 什么功能是用C语言替换字符串中的子字符串?

c++ - 获取字符串文字的字符长度

python - 如何提取特定单词周围的文本片段?

python - 获取 K 组 N 成员和 L 组 M 成员的组合列表

list - F#中元素的最优雅组合

javascript - 使用python将base64字符串转换为png图像

python - 我可以通过将函数应用于具有多重处理的数据对象中的项目来提高性能吗?

python - 覆盖 Django 用户管理器以仅返回查询中的事件用户

Java 子列表无序排列组合