【问题标题】:Why does itertools.permutations() return a list, instead of a string?Python Itertools.Permutations()
【发布时间】:2011-11-13 18:27:33
【问题描述】:

为什么 itertools.permutations() 为每个排列返回一个字符或数字的列表,而不是只返回一个字符串?

例如:

>>> print([x for x in itertools.permutations('1234')])
>>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]

为什么不返回这个?

>>> ['1234', '1243', '1324' ... ]

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    itertools.permutations() 就是这样工作的。它接受一个任意的迭代作为参数,并且总是返回一个产生元组的迭代器。它没有(也不应该)特殊情况的字符串。要获取字符串列表,您始终可以自己加入元组:

    list(map("".join, itertools.permutations('1234')))
    

    【讨论】:

    • 如果不是列表 comp、gen-expr 或其他方法,为什么还要使用 map。
    • 我认为map("".join, itertools.permutations('1234')) 就足够了。添加 list() 没有任何区别。
    • @BillCheng 在 Python 2 中,map() 的结果已经是一个列表,这是真的,但是这个问题是关于 Python 3 的。在大多数情况下,您应该能够使用生成器在 Python 3 中由 map() 返回的对象,但为了便于测试,我将显式转换添加到列表中。
    【解决方案2】:

    因为它需要一个可迭代的参数并且不知道它是一个字符串。该参数在文档中有所描述。

    http://docs.python.org/library/itertools.html#itertools.permutations

    【讨论】:

      【解决方案3】:

      也可以对字符串和列表进行Perumatation,下面是示例..

      x = [1,2,3]
      

      如果您需要对上述列表进行排列

      print(list(itertools.permutations(x, 2)))
      
      # the above code will give the below..
      # [(1,2),(1,3),(2,1)(2,3),(3,1),(3,2)]
      

      【讨论】:

        【解决方案4】:

        我没有尝试过,但很可能应该可以工作

        comb = itertools.permutations("1234",4)
        for x in comb: 
          ''.join(x)    
        

        【讨论】:

          猜你喜欢
          • 2011-02-03
          • 1970-01-01
          • 2021-09-29
          • 1970-01-01
          • 2019-09-14
          • 1970-01-01
          • 2020-03-03
          • 1970-01-01
          • 2011-09-25
          相关资源
          最近更新 更多