检查两个元组在其对应的位置是否有相同的元素

2024-09-28 01:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是:

pair1 = (1,2)
pair2 = (3,3)
pair3 = (3,2)

# Is there a way that I can compare any of these two objects and yields the following:
 def myComp(...):
 #...

myComp(pair1,pair2) gives False 
myComp(pair1,pair3) gives True     #They both have 2 at index 1
myComp(pair1,pair3) gives True     #They both have 3 at index 0

任何想法或建议将不胜感激。在


Tags: trueindexthatishavewayatthere
2条回答

有一些内置函数可以比硬编码if语句条件容易得多。您可以使用zipany

def myComp(pair1, pair2):
    return any(x == y for x, y in zip(pair1, pair2))

^{pr2}$

结果是,使用zip将这两个列表压缩在一起,这将创建一个元组生成器。这是在生成器理解中解包的。any然后测试是否有任何比较x == y是{}。如果是,则结果是True,并返回。否则,返回False。在

这种方法适用于任意大小的列表,只要它们相等。在

您的mycmp函数只需要一个if-to-do比较,因此它将如下所示:

def myComp(pair1,pair2)
   if (pair1[0]==pair2[0] || pair1[1]==pair2[1])
       return true;
return false;

相关问题 更多 >

    热门问题