Python 如何检查列表元素是否在另一个列表中,但也在同一个索引中

Python 如何检查列表元素是否在另一个列表中,但也在同一个索引中,python,python-2.7,Python,Python 2.7,我需要检查两个列表是否有任何相同的元素,但这些相同的元素也必须位于相同的索引位置 我想出了一个丑陋的解决方案: def check_any_at_same_index(list_input_1, list_input_2): # set bool value check_if_any = 0 for index, element in enumerate(list_input_1): # check if any elements are the same

我需要检查两个列表是否有任何相同的元素,但这些相同的元素也必须位于相同的索引位置

我想出了一个丑陋的解决方案:

def check_any_at_same_index(list_input_1, list_input_2):
    # set bool value
    check_if_any = 0
    for index, element in enumerate(list_input_1):
        # check if any elements are the same and also at the same index position
        if element == list_input_2[index]:
            check_if_any = 1
    return check_if_any

if __name__ == "__main__":
    list_1 = [1, 2, 4]
    list_2 = [2, 4, 1]
    list_3 = [1, 3, 5]

    # no same elements at same index
    print check_any_at_same_index(list_1, list_2)
    # has same element 0
    print check_any_at_same_index(list_1, list_3)
必须有更好更快的方法来执行此操作,有什么建议吗?

如果要检查同一索引中是否有任何相等的项,可以使用
zip()
函数和
any()
中的生成器表达式

any(i == j for i, j in zip(list_input_1, list_input_2))
如果要返回该项目(第一次出现),可以使用
next()

如果要检查所有选项,可以使用简单的比较:

list_input_1 == list_input_2

我想OP想要
所有的
。是的。。。如果结果有[True,False,False]任何一个为True。。。应该是all@DeepSpace当你检查代码时,它似乎不是这样@IljaEverilä当然,刚刚修好;-)
list_input_1 == list_input_2