gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:04:13 24 4
gpt4 key购买 nike

我为此搜索了 stackoverflow,但找不到解决方法。它可能涉及 itertools。

我想找到拆分字符串的所有可能结果,比如将字符串 thisisateststring 分成 n (等长或不等长,无所谓,都应该是包括)字符串。

例如让n3:

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

最佳答案

您可以在此处使用 itertools.combinations。您只需选择两个 split 点来生成每个结果字符串:

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]

输出:

['t', 'h', 'isisateststring']
['thisisateststri', 'n', 'g']

关于python - 拆分为 n 个字符串时返回字符串的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22915726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com