问题描述
我对此进行了搜索stackoverflow,但找不到解决方法.它可能涉及itertools.
I made a search for stackoverflow about this but couldn't find a way to do it. It probably involves itertools.
我想找到将字符串分割的所有可能结果,例如将字符串thisisateststring
转换为n
(长度相等或不相等,都无所谓,都应包括在内)字符串.
I want to find all the possible results of splitting a string, say the string thisisateststring
into n
(equal or unequal length, doesn't matter, both should be included) strings.
例如,让n
为3
:
[["thisisat", "eststrin", "g"], ["th", "isisates", "tstring"], ............]
推荐答案
在itertools.combinations()
中,在结果中包含空字符串会很尴尬.编写自己的递归版本可能是最简单的:
Including empty strings in your results will be rather awkward with itertools.combinations()
. It's probably easiest to write your own recursive version:
def partitions(s, k):
if not k:
yield [s]
return
for i in range(len(s) + 1):
for tail in partitions(s[i:], k - 1):
yield [s[:i]] + tail
这将适用于任意字符串s
的任意数量k
的所需分区.
This will work for any number k
of desired partitions for any string s
.
这篇关于拆分为n个字符串时,返回字符串的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!