【问题标题】:Generate all combinations of strings and their substrings in a set -- python在集合中生成字符串及其子字符串的所有组合——python
【发布时间】:2015-06-10 21:51:35
【问题描述】:

我想从一组字符串中获取所有字符串组合。例如:

permut = set()
permut.add("D")
permut.add("C")

def getAllKombos(stuff):
    returnvalue = set()
    for L in range(0, len(stuff) + 1):
        for subset in itertools.combinations(stuff, L):
            for i in subset:
                x = x + (str(i))
                returnvalue.add(x)
            x = ""
    return returnvalue

print getAllKombos(permut)

我的输出是:

set(['C', 'D', 'CD'])

但我需要

set(['C', 'D', 'CD', 'DC'])

我不明白我做错了什么

【问题讨论】:

标签: python string set combinations


【解决方案1】:
import itertools

permut = set()
permut.add("D")
permut.add("C")

def getAllKombos(stuff):
    returnvalue = set()
    for L in range(0, len(stuff) + 1):
        for subset in itertools.permutations(stuff, L):
            for i in subset:
                x = x + (str(i))
                returnvalue.add(x)
            x = ""
    return returnvalue

print getAllKombos(permut)

这段代码现在可以工作了,你所要做的就是将组合切换到排列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多