[英]how to check whether a list element is in another list but also at the same index
我需要检查两个列表是否具有相同的元素,但这些相同的元素也必须位于相同的索引位置。
我想出了一个以下丑陋的解决方案:
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)
有什么更好的方法可以做到这一点,任何建议?
如果要检查同一索引中是否存在任何相等的项,则可以在any()
使用zip()
函数和生成器表达式。
any(i == j for i, j in zip(list_input_1, list_input_2))
如果要返回该项(第一次出现),可以使用next()
:
next((i for i, j in zip(list_input_1, list_input_2) if i == j), None)
如果你想检查所有你可以使用一个简单的比较:
list_input_1 == list_input_2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.