返回一个字符串拆分为 n 个字符串时所有可能的组合

2023-12-02

我在 stackoverflow 上搜索了相关内容,但找不到方法。可能涉及到itertool。

我想找到分割字符串的所有可能结果,比如字符串thisisateststring into n(长度相等或不等,无关紧要,两者都应该包含)字符串。

例如让n be 3:

[["thisisat", "eststrin", "g"], ["th", "isisates", "tstring"], ............]

您可以使用itertools.combinations这里。您只需选择两个分割点即可生成每个结果字符串:

from itertools import combinations
s = "thisisateststring"
pools = range(1, len(s))
res = [[s[:p], s[p:q], s[q:]] for p, q in combinations(pools, 2)]
print res[0]
print res[-1]

Output:

['t', 'h', 'isisateststring']
['thisisateststri', 'n', 'g']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回一个字符串拆分为 n 个字符串时所有可能的组合 的相关文章

随机推荐