如何合并以下元组?
(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)
然后合并这四个元组,等等。 是否有可能动态地执行此操作,直到遇到停止条件?
答案 0 :(得分:0)
尝试使用product
from itertools import product
a = (1, 2),(5, 6) ,(3, 4)
result = list(product(*a))
答案 1 :(得分:0)
是的,可能的
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)
您可以使用递归,因此对于任何输入维只需要几个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]]