2016-10-31 59 views
1

我想要拿出優雅的代碼來創建來自單個字符的字符的組合/排列:字符的組合和排列

例如,從單一的角色,我想代碼來創建這些排列(結果的順序並不重要):

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

我我不認爲這可能是一個更好的解決方案。

那麼,你能幫我找到最理想的/ pythonic的方式來達到預期的效果嗎?

回答

1

您可以簡單地使用itertools.product不同repeat值來獲得期望的結果

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

哦,我喜歡它。雖然我會這樣做,以使其更簡單: pop + [''.join(item)for product in product(pop,repeat = 2)] –

+0

@JayMarm我提供的答案是一個通用的答案。您可以根據自己的需求進行定製。 – thefourtheye