返回字符串的所有可能组合

返回字符串的所有可能组合

本文介绍了拆分为n个字符串时,返回字符串的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此进行了搜索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.

例如,让n3:

[["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个字符串时,返回字符串的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 01:18