从成对创建元组

为什么:

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

这是我想收到的示例:

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)  

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

hilberts_drinking_problem:

这是一个丑陋的单线。

first_tuple = (1, 2)
second_tuple = (4, 5)
tups = [first_tuple, second_tuple]
res = [(i, j) for x in tups for y in tups for i in x for j in y if x is not y]
# [(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (4, 2), (5, 1), (5, 2)]

除非您将其用于运动,否则可能应该选择一种更具可读性的解决方案,例如下面MrGeek提出的解决方案。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章