下面是一个示例代码,用于比较两个不等长度的字符列表是否相等:
def is_matching(list1, list2):
# 如果两个列表的长度不相等,则直接返回False
if len(list1) != len(list2):
return False
# 使用zip函数将两个列表中的元素一一对应起来进行比较
for char1, char2 in zip(list1, list2):
if char1 != char2:
return False
# 如果循环结束后没有返回False,则说明两个列表是相等的
return True
# 测试示例
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'b', 'c', 'd']
print(is_matching(list1, list2)) # 输出 True
list3 = ['a', 'b', 'c', 'd', 'e']
list4 = ['a', 'b', 'c', 'd']
print(is_matching(list3, list4)) # 输出 False
这个示例代码中的is_matching
函数接受两个字符列表作为参数,首先通过比较它们的长度来判断是否相等,如果长度不相等,则直接返回False
。然后,使用zip
函数将两个列表中的元素一一对应起来进行比较,如果有任何一个对应的字符不相等,则返回False
。如果循环结束后没有返回False
,则说明两个列表是相等的,返回True
。最后,通过测试示例来验证这个函数的正确性。