This question already has answers here:
How to generate all permutations of a list?
                                
                                    (31个答案)
                                
                        
                        
                            Finding all possible case permutations in Python
                                
                                    (1个答案)
                                
                        
                                5年前关闭。
            
                    
如何在python中获取所有可能的大小写组合以及字符串的字母?



输入:'ab'输出:aB','Ba','BA','Ab','AB','bA'

输入:'dan'输出:aND','ANd','Dna','naD','DaN','aDn','Adn','dnA','NdA','anD','DnA', 'NAD','nAD','Dan','NDA','nAd','AdN','DAn','AnD','And','DNA','daN','adN','nDa ','dAN','dNa','aDN','ADN','dNA','Nda','AND','DNa','NaD','Nad','aNd','nDA', 'dAn','NAd','ndA','NDa','ADn','DAN'

最佳答案

这可以使用itertools完成

from itertools import permutations
def perm(word):
    perms = [''.join(p) for p in permutations(word)]
    print(perms)
    return perms

def capPer(arrPerm):
    result=[]
    for val in arrPerm:
        wordList=list(val)

        for i,letter in enumerate(wordList):
            wordList[i]=letter.upper()
            result.extend(perm(''.join(wordList)))
    return set(result)

def combi(wrd):
    print(capPer(perm(wrd)))


combi('ab')
combi('dan')

**output:**
set(['aB', 'Ba', 'BA', 'Ab', 'AB', 'bA'])
set(['aND', 'ANd', 'Dna', 'naD', 'DaN', 'aDn', 'Adn', 'dnA', 'NdA', 'anD', 'DnA', 'NAD', 'nAD', 'Dan', 'NDA', 'nAd', 'AdN', 'DAn', 'AnD', 'And', 'DNA', 'daN', 'adN', 'nDa', 'dAN', 'dNa', 'aDN', 'ADN', 'dNA', 'Nda', 'AND', 'DNa', 'NaD', 'Nad', 'aNd', 'nDA', 'dAn', 'NAd', 'ndA', 'NDa', 'ADn', 'DAN'])

关于python - 如何在python中获取字母的所有排列以及字符串的大小写? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23750204/

10-12 20:17