python - Python:使用空格生成多个字符串组合
问题描述
我有一个包含 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
功能由@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']
推荐阅读
- android-jetpack-compose - Jetpack Compose - 滚动到列中的重点可组合
- ffmpeg - 将一堆 .pkl 文件合并为一个,然后转换为 .fbx(在 Windows 上)
- java - 区间中的随机数,边界接近最大和最小整数值
- java - 多线程写入套接字输出流时丢失消息
- python - 用 flask_pymongo 初始化数据库的正确方法是什么?
- kofax - 如何从 KTM 脚本更改 Kofax 批处理优先级
- c# - 如何在文件中添加新文本行而不丢失旧内容
- javascript - 通过 p5 重绘画布并删除旧画布
- python - 如何在 KivyMD (Python) 中结合导航抽屉和多个屏幕?
- ios - 如何在 Swift 中一一显示 UITextField?