【问题标题】:find all possible combinations of letters in a string in python [duplicate]在python中查找字符串中所有可能的字母组合[重复]
【发布时间】:2015-03-09 05:13:30
【问题描述】:

我在 python 中有一个字符串, 我需要找到该字符串的任何子字符串(包括其自身)的所有可能方式 可以选择。子字符串(出于我的目的)在原始字符串中不必是连续的——它可能有间隙。
例如:"frogman" 是此定义下"froghuman' 的众多子字符串之一。

例如 will 函数: 如果我的字符串是"abcd",输出应该是:

[ "a", "b", "c", "d", "ab", "ac", "ad", "bc", "bd", "cd", "abc", "abd", "acd", "bcd", "abcd" ]

【问题讨论】:

标签: python string substring


【解决方案1】:

您的示例输入/输出表明您正在寻找power set。你可以generate a power set for a string using itertools module in Python:

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

print(list(map(''.join, powerset('abcd'))))

输出

['',
 'a',
 'b',
 'c',
 'd',
 'ab',
 'ac',
 'ad',
 'bc',
 'bd',
 'cd',
 'abc',
 'abd',
 'acd',
 'bcd',
 'abcd']

注意:输出包含空字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2015-05-06
    • 2019-11-04
    • 2023-04-04
    相关资源
    最近更新 更多