字符的组合和排列

Combinations and Permutations of characters

我正在尝试编写优雅的代码,从单个字符创建 combinations/permutations 个字符:

例如从单个字符我想要代码来创建这些排列(结果的顺序并不重要):

'a' ---->  ['a', 'aa', 'A', 'AA', 'aA', 'Aa']

目前为止我遇到的不太优雅的解决方案:

# this does it...
from itertools import permutations
char = 'a'
p = [char, char*2, char.upper(), char.upper()*2]
pp = [] # stores the final list of permutations
for j in range(1,3):
    for i in permutations(p,j):
        p2 = ''.join(i)
        if len(p2) < 3:
            pp.append(p2)
print pp
['a', 'aa', 'A', 'AA', 'aA', 'Aa']

#this also works...
char = 'a'
p = ['', char, char*2, char.upper(), char.upper()*2]
pp = [] # stores the final list of permutations
for i in permutations(p,2):
    j = ''.join(i)
    if len(j) < 3:
        pp.append(j)
print list(set(pp))
['a', 'aa', 'aA', 'AA', 'Aa', 'A']

# and finally... so does this:
char = 'a'
p = ['', char, char.upper()]
pp = [] # stores the final list of permutations
for i in permutations(p,2):
    pp.append(''.join(i))
print list(set(pp)) + [char*2, char.upper()*2]
['a', 'A', 'aA', 'Aa', 'aa', 'AA']

我不太擅长 lambda,我怀疑这可能是更好的解决方案。

那么,你能帮我找到最 elegant/pythonic 达到预期结果的方法吗?

您只需使用具有不同 repeat 值的 itertools.product 即可获得预期结果

>>> pop = ['a', 'A']
>>> from itertools import product
>>> [''.join(item) for i in range(len(pop)) for item in product(pop, repeat=i + 1)]
['a', 'A', 'aa', 'aA', 'Aa', 'AA']