【问题标题】:How to get all combination from multiple lists?如何从多个列表中获取所有组合?
【发布时间】:2017-05-25 08:37:57
【问题描述】:

我不确定我的问题是否正确,但我不知道如何解释。 所以我有一些列表,比如

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

我需要得到类似的东西:

result = [
    ['11', '21', '31'],
    ['11', '21', '32'],
    ['11', '22', '31'],
    ['11', '22', '32'],
    ['12', '21', '31'],
    ['12', '21', '32'],
    ['12', '22', '31'],
    ['12', '22', '32']
]

【问题讨论】:

  • 请先尝试自己研究您的问题,将您的问题标题复制到 google 会产生多个重复项。
  • 如果所有列表的长度都为 2,那么它看起来像一个二进制计数系统,因此您可以使用算法来做到这一点,但使用 itertools 的帖子是正确的。

标签: python


【解决方案1】:

用户itertoolscombinations

import itertools
a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
list(itertools.combinations(itertools.chain(a,b,c), 3))
[('11', '12', '21'), ('11', '12', '22'), ('11', '12', '31'), ('11', '12', '32'), ('11', '21', '22'), ('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('11', '31', '32'), ('12', '21', '22'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32'), ('12', '31', '32'), ('21', '22', '31'), ('21', '22', '32'), ('21', '31', '32'), ('22', '31', '32')]

product:

list(itertools.product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]

【讨论】:

  • combinations 留下一些使用相同列表的 2 个元素的结果。
【解决方案2】:

你需要itertools.product 它返回输入迭代的笛卡尔积。

>>> a = ['11', '12']
>>> b = ['21', '22']
>>> c = ['31', '32']
>>>
>>> from itertools import product
>>>
>>> list(product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]

您可以使用列表推导将元组转换为列表:

>>> [list(i) for i in product(a,b,c)]
[['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21', '32'], ['12', '22', '31'], ['12', '22', '32']]

【讨论】:

    【解决方案3】:
    import itertools
    list(itertools.product(a,b,c))
    

    或者使用 numpy

    import numpy
    [list(x) for x in numpy.array(numpy.meshgrid(a,b,c)).T.reshape(-1,len(a))]
    

    【讨论】:

      【解决方案4】:
      import numpy as np    
      np.array(np.meshgrid(a, b, c)).T.reshape(-1,3)
      

      编辑

      import numpy as np 
      len = 3 #combination array length
      np.array(np.meshgrid(a, b, c)).T.reshape(-1,len)
      

      【讨论】:

        猜你喜欢
        • 2015-08-11
        • 1970-01-01
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多