Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中查找所有可能的大小写排列_Python_String_Permutation_Case Insensitive - Fatal编程技术网

在Python中查找所有可能的大小写排列

在Python中查找所有可能的大小写排列,python,string,permutation,case-insensitive,Python,String,Permutation,Case Insensitive,我需要返回python中字符串的所有可能的大小写排列的列表 例如,输入“ar”应返回: [ 'ar','Ar','aR','AR'] 或“弧”: 您可以通过使用大写和小写字母并采用其笛卡尔坐标来实现这一点: 要直观了解其工作原理,请执行以下操作: zip正在为我们创建3个“轴”,每个轴有2个点(大写/小写): product采用这些轴的笛卡尔积,即它创建的单位立方体的角对应的8个可能坐标: 1.创建轴 2.以笛卡尔积为例 你要求的基本上是一个算法,如果你知道这个算法,你可以用你想要的

我需要返回python中字符串的所有可能的大小写排列的列表

例如,输入
“ar”
应返回:

[ 'ar','Ar','aR','AR']  
“弧”


您可以通过使用大写和小写字母并采用其笛卡尔坐标来实现这一点:


要直观了解其工作原理,请执行以下操作:

  • zip
    正在为我们创建3个“轴”,每个轴有2个点(大写/小写):
  • product
    采用这些轴的笛卡尔积,即它创建的单位立方体的角对应的8个可能坐标:
  • 1.创建轴 2.以笛卡尔积为例
    你要求的基本上是一个算法,如果你知道这个算法,你可以用你想要的任何语言(Python)实现它。我能帮你做的就是:递归。(在纸上试一些东西可能会有帮助)@nekosune:出于好奇,你用这个功能干什么?我担心的是,也许你用这个来比较一个未知大小写的字符串,看看它是否匹配一个单词。如果是这样的话,还有更好的方法可以做到这一点。@Bryan不,如果我使用tolower,我使用的是app engine,希望返回一个对大小写不敏感的查询,使用GQL的in部分来返回,因为它被认为是短词。最简单的方法是
    itertools.product(*zip(string.lower(),string.upper())
    。非常感谢,这太完美了。算法,尤其是递归算法一直是我的弱点。我有点困惑。比较大写/小写字母(因为
    'a'
    永远不应该等于
    'a'
    )和切分第一个字符(与
    输入字符串[0]
    )有什么意义?避免在有一个没有上下区别的字符时返回两个结果,例如,
    '.upper()='.lower()
    [ 'arc','Arc','ARc','aRc','aRC','ARC']
    
    def all_casings(input_string):
        if not input_string:
            yield ""
        else:
            first = input_string[:1]
            if first.lower() == first.upper():
                for sub_casing in all_casings(input_string[1:]):
                    yield first + sub_casing
            else:
                for sub_casing in all_casings(input_string[1:]):
                    yield first.lower() + sub_casing
                    yield first.upper() + sub_casing
    
    >>> [x for x in all_casings("foo")]
    ['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
    >>> list(all_casings("foo"))
    ['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
    
    import itertools
    
    chars = "abc"
    results = list(map(''.join, itertools.product(*zip(chars.upper(), chars.lower()))))
    
    print(results)
    >>>['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
    
    [('A', 'a'), 
     ('B', 'b'), 
     ('C', 'c')]