对比两个列表元素差异时如何正确校验重复字母
重复字母校验逻辑修正方案
原有代码缺陷
all(elem in list1 for elem in list2)逻辑仅校验list2中的元素是否在list1中存在,不统计元素出现次数。哪怕list2包含2个"b"、list1仅含1个"b",该判断也会错误返回真值,无法支持重复元素的匹配校验。
实现方案
方案1:Counter频次统计(推荐)
调用Python标准库collections.Counter统计两个列表的元素出现次数,校验list2内每个元素的出现次数均不超过list1对应元素的出现次数即可,天然支持重复字母校验:
from collections import Counter list1 = ["a", "b", "b"] list2 = ["a", "b"] count1 = Counter(list1) count2 = Counter(list2) if all(count2[item] <= count1[item] for item in count2): print("they have all the same letters")
如果需要触发「list2存在第二个"b"才执行打印」的逻辑,直接将list2修改为["a", "b", "b"]即可,上述代码会自动校验list1中"b"的数量是否满足要求。
方案2:手动遍历校验(无依赖)
不引入额外模块的情况下,可以通过副本移除的方式实现校验:遍历list2的每个元素,每匹配到一个值就从list1的副本中删除对应元素,中途找不到匹配项直接判定校验失败:
list1 = ["a", "b", "b"] list2 = ["a", "b"] def check_match(source, target): source_tmp = source.copy() for item in target: if item not in source_tmp: return False source_tmp.remove(item) return True if check_match(list1, list2): print("they have all the same letters")
运行上述任意一段代码,传入给出的示例参数,都会输出预期结果:
they have all the same letters
内容的提问来源于stack exchange,提问作者Soapy
相关产品推荐
相关产品推荐

