我需要在python中构建一个函数,该函数输入两个元组并返回所有可能的对。
def mult_tuple(tuple1,tuple2):
让元组为:
first_tuple = (1,2)
second_tuple = (4,5)
,输出将是:
((1,4),(4,1),(1,5),(5,1),(2,4),(4,2),(2,5),(5,2))
注意:输入的元组可以是任何大小。例如:(1,4) and (8,2,9,6)
答案 0 :(得分:2)
您可以使用product
中的itertools
import itertools
for element in itertools.product((1,2),(3,4,5,6)):
print(element, (element[1],element[0]))
输出将是:
(1, 3) (3, 1)
(1, 4) (4, 1)
(1, 5) (5, 1)
(1, 6) (6, 1)
(2, 3) (3, 2)
(2, 4) (4, 2)
(2, 5) (5, 2)
(2, 6) (6, 2)
例如,您的功能将
def mult_tuple(tuple1,tuple2):
for element in itertools.product(tuple1, tuple2):
yield element
yield (element[1],element[0])
您可以在此处获取更多信息 https://docs.python.org/3/library/itertools.html#itertools.product