赞
踩
一、问题场景:
要比较两个列表list_A、list_B,以便创建一个新列表,新列表中存储list_B元素没有出现在list_A中的内容。例如:
new_list=[] list_A=["a", "b", "c", "d", "e"] list_B=["b", "d", "f", "m"]
结果应该是:
new_list=["f", "m"]
二、分析思路:
方案一:利用列表循环的方法,将list_B中的元素在list_A中进行循环查找,将不再列表list_A中的元素识别出来,这个方案的复杂度为O(n)。
方案二:利用集合,将list_A转换成集合方式,然后在进行循环遍历,这个方案的复杂度为O(1)
三、实现代码:
方案一:
new_list = [item for item in list_B if item not in list_A]
方案二:
set_A = set(list_A) # 利用无序的概念降低复杂度 new_list = [item for item in list_B if item not in set_A]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。