代码之家  ›  专栏  ›  技术社区  ›  Michael Adlhoch

如何在python中组合元组

  •  1
  • Michael Adlhoch  · 技术社区  · 7 年前

    如何组合下列元组?

    (1, 2); (5, 6) ; (3, 4)

    解决方案应该是:

    (1, 5, 3); (1, 5, 4); (1, 6, 3); (1, 6, 4); (2, 5, 3); (2, 5, 4); (2, 6, 3); (2, 6, 4)

    从一开始我就 m = 3 元组。元组的数量随着每次迭代而增加,在每次迭代之后,将添加一个用于重新组合的新元组。在第一次迭代之后,我得到:

    (1, 2); (5, 6); (3, 4); (9, 10)

    然后组合这4个元组等等。 是否有可能动态执行此操作,直到达到停止条件?

    3 回复  |  直到 7 年前
        1
  •  0
  •   shahin mahmud    7 年前

    是的,这是可能的

    from itertools import product
    for i in range(your_limit):
        your_tuples_container.append(your_new_tuple)
        result = list(product(*your_tuples_container))
    
        2
  •  0
  •   Mel    7 年前

    试试看 product

    from itertools import product
    a = (1, 2),(5, 6) ,(3, 4)
    result = list(product(*a))
    
        3
  •  0
  •   Ajax1234    7 年前

    可以使用递归,因此只需要几个 for 任何输入维度的循环:

    l = [(1, 2), (5, 6), (3, 4)]
    def cartesian_product(d, current = []):
      if not d[1:]:
        yield [i+[b] for i in current for b in d[0]]
      else:
        yield from cartesian_product(d[1:], [i+[b] for i in current for b in d[0]])
    
    print(list(cartesian_product(l[1:], list(map(lambda x:[x], l[0]))))[0])
    

    输出:

    [[1, 5, 3], [1, 5, 4], [1, 6, 3], [1, 6, 4], [2, 5, 3], [2, 5, 4], [2, 6, 3], [2, 6, 4]]