分离字符串

 Rozenia 发布于 2023-02-08 13:17

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

例如:

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

我有点坚持如何生成所有可能的列表.组合将只给出包含字符串集子集长度的列表,排列将提供所有可能的订购方式.

由于遍历切片,我可以在列表中只使用一个逗号来创建所有情况,但是我不能用两个逗号来表示例如"ab","c","d"和"a","b" ,"光盘"

我的尝试w/slice:

test="abcd"

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

DSM.. 15

怎么样的:

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']


Tim Peters.. 15

你当然可以使用itertools它,但我认为直接编写递归生成器更容易:

def gen_commas(s):
    yield s
    for prefix_len in range(1, len(s)):
        prefix = s[:prefix_len]
        for tail in gen_commas(s[prefix_len:]):
            yield prefix + "," + tail

然后

print list(gen_commas("abcd"))

版画

['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']

我不确定为什么我觉得这更容易.也许只是因为直接做到这一点很容易;-)

2 个回答
  • 怎么样的:

    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']
    

    2023-02-08 13:18 回答
  • 你当然可以使用itertools它,但我认为直接编写递归生成器更容易:

    def gen_commas(s):
        yield s
        for prefix_len in range(1, len(s)):
            prefix = s[:prefix_len]
            for tail in gen_commas(s[prefix_len:]):
                yield prefix + "," + tail
    

    然后

    print list(gen_commas("abcd"))
    

    版画

    ['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']
    

    我不确定为什么我觉得这更容易.也许只是因为直接做到这一点很容易;-)

    2023-02-08 13:20 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有