【问题标题】:Combinations and Permutations of characters字符的组合和排列
【发布时间】: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


    【解决方案1】:

    您可以简单地使用具有不同 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']
    

    【讨论】:

    • 哦,我喜欢。虽然我会这样做以使其不那么复杂:pop + [''.join(item) for item in product(pop, repeat=2)]
    • @JayMarm 我提供的答案是通用的。您可以根据需要对其进行自定义。
    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多