gpt4 book ai didi

python - 从对中创建一个元组

转载 作者:行者123 更新时间:2023-12-03 01:07:32 25 4
gpt4 key购买 nike

我想创建一个元组,它显示两个元组中所有可能的对

这是我希望收到的示例:

first_tuple = (1, 2)
second_tuple = (4, 5)
mult_tuple(first_tuple, second_tuple)

输出:

((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))

这就是我所做的,虽然成功了,但看起来有点麻烦:

def mult_tuple(tuple1, tuple2):
ls=[]
for t1 in tuple1:

for t2 in tuple2:
c=(t1,t2)
d=(t2,t1)
ls.append(c)
ls.append(d)

return tuple(ls)


first_tuple = (1, 2)
second_tuple = (4, 5)
mult_tuple(first_tuple, second_tuple)

我编写的代码有效,但是我正在寻找更好的代码
预先感谢您

最佳答案

您可以使用itertoolsproductpermutations :

from itertools import product, permutations

first_tuple, second_tuple = (1, 2), (4, 5)

result = ()

for tup in product(first_tuple, second_tuple):
result += (*permutations(tup),)

print(result)

输出:

((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))

product 生成由嵌套 for 循环结构(您的 t1t2 变量)同等生成的元组(两个元素),并且 permutations 生成由 cd 变量同等生成的两个排列。

关于python - 从对中创建一个元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com