字符的组合和排列

时间:2016-10-31 05:04:17

标签: python python-2.7 itertools cartesian-product

我正在尝试提供优雅的代码,从单个字符创建字符的组合/排列:

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

'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']

我对lambdas并不满意,我怀疑这可能是一个更好的解决方案所在。

那么,你能帮我找到最优雅/ pythonic的方法来获得理想的结果吗?

1 个答案:

答案 0 :(得分:1)

您只需使用itertools.productrepeat值来获得预期的结果

>>> 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']