python2.7中使用itertools的字母组合

2024-04-25 23:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用itertools.组合返回字母表中长度不超过n的所有字母组合

def string_combinations(alphabet, n):
    '''
    Parameters
    ----------
    alphabet : {str}
    n : {int}

    Returns
    -------
    list : {list} of {str}    

    Example
    -------
    >>> string_combinations('abc', 2)
    ['a', 'b', 'c', 'ab', 'ac', 'bc']
    '''

到目前为止我已经

return [str(x) for i in range(1,n+1) for x in itertools.combinations(alphabet,i)]

但是itertools.combinations返回列表中的元组[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c')]我应该如何实现我想要的解决方案?你知道吗


Tags: ofinforstringdef字母表listreturns
1条回答
网友
1楼 · 发布于 2024-04-25 23:20:22

可以连接itertools返回的所有字符串:

result = map("".join, (comb for i in range(1, n+1) for comb in itertools.combinations(alphabet, i)))

这相当于在列表中调用"".join

result = ["".join(comb) for ...]

"".join(iterable)连接从iterable检索的所有字符串:

"".join(('a', 'b', 'c')) == "abc"

相关问题 更多 >

    热门问题