比较元组的元素

时间:2018-08-09 13:02:43

标签: python python-3.x tuples

我要比较两个元组T1T2,它们都是三元组,首先比较T[0],如果比较T1[0]==T2[0],然后比较{{ 1}}和T1[1],如果T2[1],则比较T1[1]==T2[1]T1[2]

4 个答案:

答案 0 :(得分:1)

条件比较

如果您希望有条件地检查2个元组的每个索引是否相等,则可以使用for循环和break,当值不匹配时:

a = (1, 2, 3)
b = (1, 4, 3)

for idx, (i, j) in enumerate(zip(a, b)):
    if i == j:
        print(f'Index {idx} match: {i}')
    else:
        print(f'Index {idx} no match: {i} vs {j}')
        break

结果:

Index 0 match: 1
Index 1 no match: 2 vs 4

逐元素比较

您可以对zip使用元组理解:

res = tuple(i == j for i, j in zip(a, b))

# (True, False, True)

或者,您可以转换为NumPy数组并检查相等性:

import numpy as np

res = np.array(a) == np.array(b)

# array([ True, False,  True], dtype=bool)

元组的平等

当然,要测试2个元组的 all 个元素是否相等,只需检查a == b

答案 1 :(得分:1)

要解决此问题,您必须像下面一样使用if-else ladder

tup1=(1,2,3)
tup2=(1,3,4)
if(tup1[0]==tup2[0]):
    print("Elements at index 0 are same")
    if(tup1[1]==tup2[1]):
        print("Elements at index 1 are same")
        if(tup1[2]==tup2[2]):
            print("Elements at index 2 are same")
        else:
            print("Elements at index 2 are same")
    else:
        print("Elements at index 1 are not same")
else:
    print("Elements at index 0 are not same")

答案 2 :(得分:0)

尝试使用break循环:

for i in range(len(a)):
    if a[i] == b[i]:
        pass
    else:
        break
print i

答案 3 :(得分:0)

您可以使用while循环来控制是否应该比较下一对:

T1 = (1,2,3)
T2 = (1,4,5)

def compareTuples(T1, T2):
    index = 0
    length = len(T1)
    while index < length:
        # If they are equal, move to the next pair, else stop.
        if T1[index]==T2[index]:
            index += 1
        else:
            return False
    return True