在Python中,比较两个列表中每个值的索引可以通过以下步骤完成:
enumerate()
函数遍历其中一个列表,并同时获取每个值和对应的索引。index()
方法查找该值的索引。以下是一个示例代码:
def compare_lists(list1, list2):
if len(list1) != len(list2):
return False
for value, index in enumerate(list1):
if list2.index(value) != index:
return False
return True
# 测试
list1 = [1, 2, 3, 4]
list2 = [1, 2, 3, 4]
print(compare_lists(list1, list2)) # 输出:True
list3 = [1, 2, 3, 4]
list4 = [4, 3, 2, 1]
print(compare_lists(list3, list4)) # 输出:False
请注意,在使用index()
方法查找索引时,如果列表中存在重复值,将返回第一个匹配的索引。如果两个列表中存在相同值但位置不同,以上比较方法将会返回False
。
希望以上回答对您有帮助!如果有任何进一步的问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云