【问题标题】:How to calculate a Cartesian product of a list with itself [duplicate]如何计算列表自身的笛卡尔积[重复]
【发布时间】:2017-04-26 13:40:24
【问题描述】:

例如,

list = [0, 1, 2]

我想要一个所有可能的 2 组合的列表:

combinations = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

在我看来,Python 中 itertools 中的所有工具都只生成 (1,0) 和 (0,1) 之一,而不是两者,我需要两者。除了手动输入之外,还有什么建议吗?

【问题讨论】:

  • VTR,因为linked duplicate 没有覆盖repeat 参数,因此对于获取列表的乘积本身没有帮助。

标签: python list itertools cartesian-product


【解决方案1】:

可以通过导入itertools来完成:

import itertools

list1 = [0, 1, 2]
print(list(itertools.product(list1,repeat=2)))

输出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

资源: 你可以了解更多—— here

【讨论】:

    【解决方案2】:

    您正在寻找该列表与其自身的笛卡尔积,而不是排列或组合。因此你应该使用itertools.productrepeat=2

    from itertools import product
    
    li = [0, 1, 2]
    print(list(product(li, repeat=2)))
    >> [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 2011-03-24
      • 2017-03-07
      • 1970-01-01
      • 2011-01-26
      • 2016-11-22
      • 2012-02-24
      • 2011-09-18
      相关资源
      最近更新 更多