[英]combinations of letters using itertools in python2.7
I am trying to use itertools.combinations to return all the combinations of letters in alphabet with length at most n. 我正在尝试使用itertools.combinations返回最大长度为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']
'''
So far I have 到目前为止,我有
return [str(x) for i in range(1,n+1) for x in itertools.combinations(alphabet,i)]
but itertools.combinations
returns tuples in a list [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c')]
How should I achieve my desired solution? 但是itertools.combinations
返回列表[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c')]
我应该如何实现所需的解决方案?
You can concatenate all the strings returned by itertools
: 您可以连接itertools
返回的所有字符串:
result = map("".join, (comb for i in range(1, n+1) for comb in itertools.combinations(alphabet, i)))
This is equivalent to putting a call to "".join
inside a list comprehension: 这等效于在列表理解内调用"".join
:
result = ["".join(comb) for ...]
"".join(iterable)
concatenates all the string that are retrieved from an iterable: "".join(iterable)
连接从可迭代对象检索的所有字符串:
"".join(('a', 'b', 'c')) == "abc"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.