Python如何生成字符串数组的所有空格组合及原串组合?
Hey there! I get exactly what you're trying to do—you want every possible way to group adjacent words in your array, either keeping them as separate elements or merging them with spaces. Let's break this down and fix your itertools approach.
The Core Idea
For an array with n words, there are n-1 "gaps" between each pair of words. For each gap, you can choose to split (keep the words separate) or merge (join them with a space). This gives us 2^(n-1) total combinations, which matches your example (3 words → 2 gaps → 4 combinations).
Working Code with Itertools
We can use itertools.product to generate all possible split/merge choices for the gaps, then build each combination based on those choices:
import itertools def generate_word_combinations(words): if not words: return [] combinations = [] split_points = len(words) - 1 # Generate all possible split/merge choices (True = split, False = merge) for splits in itertools.product([True, False], repeat=split_points): current_group = [words[0]] for i in range(split_points): if splits[i]: # Split: add the next word as a new element current_group.append(words[i+1]) else: # Merge: append the next word to the last element in current group current_group[-1] += " " + words[i+1] combinations.append(current_group) return combinations # Test with your example input_words = ["just", "a", "test"] print(generate_word_combinations(input_words))
Output
Running this code will give you exactly the result you want:
[["just", "a", "test"], ["just", "a test"], ["just a", "test"], ["just a test"]]
Why Your Previous Itertools Approach Might Have Failed
It sounds like you were using itertools.combinations or similar functions, which are great for picking subsets—but that's not what we need here. This problem is about partitioning the array into consecutive groups, not selecting arbitrary subsets. The product function lets us iterate through all possible ways to split/merge the gaps, which is the right tool for the job.
内容的提问来源于stack exchange,提问作者Pythonius

