分隔字符串 [英] Separating a String

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

问题描述

给出一个字符串,我想生成所有可能的组合.换句话说,所有可能的方式都将逗号放在字符串中.

Given a string, I want to generate all possible combinations. In other words, all possible ways of putting a comma somewhere in the string.

例如:

input:  ["abcd"]
output: ["abcd"]
        ["abc","d"]
        ["ab","cd"]
        ["ab","c","d"]
        ["a","bc","d"]
        ["a","b","cd"]
        ["a","bcd"]
        ["a","b","c","d"]

我对如何生成所有可能的列表有些困惑.组合只会给我列出一组字符串子集的长度,排列会提供所有可能的排序方式.

I am a bit stuck on how to generate all the possible lists. Combinations will just give me lists with length of subset of the set of strings, permutations will give all possible ways to order.

由于遍历切片,我可以在列表中只用一个逗号来处理所有情况,但是我不能用"ab","c","d"和"a"之类的两个逗号来处理情况, "b","cd"

I can make all the cases with only one comma in the list because of iterating through the slices, but I can't make cases with two commas like "ab","c","d" and "a","b","cd"

我的尝试带有切片:

test="abcd"

for x in range(len(test)):
     print test[:x],test[x:]

推荐答案

诸如此类的事情

from itertools import combinations

def all_splits(s):
    for numsplits in range(len(s)):
        for c in combinations(range(1,len(s)), numsplits):
            split = [s[i:j] for i,j in zip((0,)+c, c+(None,))]
            yield split

之后:

>>> for x in all_splits("abcd"):
...     print(x)
...     
['abcd']
['a', 'bcd']
['ab', 'cd']
['abc', 'd']
['a', 'b', 'cd']
['a', 'bc', 'd']
['ab', 'c', 'd']
['a', 'b', 'c', 'd']

这篇关于分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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