【问题标题】:Python join all combinations of elements within each listPython加入每个列表中的所有元素组合
【发布时间】:2011-10-13 05:30:20
【问题描述】:

我有一个元组列表,每个元组都有两个元素:[('1','11'),('2','22'),('3','33'),...n]

一次只选择一个元组的一个元素,如何找到每个元组的所有组合?

示例结果:

[[1,2,3],[11,2,3],[11,2,3],[11,22,33],[11,2,33],[11,22,3 ],[1,22,3],[1,22,33],[1,2,33]]`

itertools.combinations 为我提供了所有组合,但不保留从每个元组中仅选择一个元素。

谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    使用itertools.product:

    In [88]: import itertools as it
    In [89]: list(it.product(('1','11'),('2','22'),('3','33')))
    Out[89]: 
    [('1', '2', '3'),
     ('1', '2', '33'),
     ('1', '22', '3'),
     ('1', '22', '33'),
     ('11', '2', '3'),
     ('11', '2', '33'),
     ('11', '22', '3'),
     ('11', '22', '33')]
    

    【讨论】:

      【解决方案2】:

      你读过itertoolsdocumentation吗?

      >>> import itertools
      >>> l = [('1','11'),('2','22'),('3','33')]
      >>> list(itertools.product(*l))
      [('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', '22', '3'), ('11', '22', '33')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-14
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 2018-05-15
        相关资源
        最近更新 更多