【发布时间】:2017-03-13 05:17:26
【问题描述】:
我正在尝试编写可以从单个字符创建字符组合/排列的优雅代码:
例如从单个字符我想要创建这些排列的代码(结果的顺序并不重要):
'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,我怀疑这可能是更好的解决方案所在。
那么,你能帮我找到达到预期结果的最优雅/pythonic 的方式吗?
【问题讨论】:
标签: python python-2.7 itertools cartesian-product