查找在Python中拆分字符串的所有列表排列 [英] Find all list permutations of splitting a string in Python

查看:193
本文介绍了查找在Python中拆分字符串的所有列表排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字母字符串,我想将其分成所有可能的组合(字母顺序必须保持固定),以便:

I have a string of letters that I'd like to split into all possible combinations (the order of letters must be remain fixed), so that:

s = 'monkey'

成为:

combinations = [['m', 'onkey'], ['mo', 'nkey'], ['m', 'o', 'nkey'] ... etc]

有什么想法吗?

推荐答案

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result

combinations = list(splitter(str))

请注意,我默认使用生成器来避免长字符串耗尽内存.

Note that I defaulted to a generator to save you from running out of memory with long strings.

这篇关于查找在Python中拆分字符串的所有列表排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆