如果元素存在,则在python中比较两个列表
发布时间:2020-12-20 11:33:42 所属栏目:Python 来源:网络整理
导读:我有两个列表,我想检查b中的元素是否存在 a=[1,2,3,4]b=[4,5,6,7,8,1] 这就是我尝试过的(尽管不起作用!) a=[1,1]def detect(list_a,list_b): for item in list_a: if item in list_b: return True return False # not founddetect(a,b) 我想检查b中是否存在
我有两个列表,我想检查b中的元素是否存在
a=[1,2,3,4] b=[4,5,6,7,8,1] 这就是我尝试过的(尽管不起作用!) a=[1,1] def detect(list_a,list_b): for item in list_a: if item in list_b: return True return False # not found detect(a,b) 我想检查b中是否存在元素,并应相应地设置一个标志.有什么想法吗? 解决方法
只要第一个元素存在于两个列表中,您的代码就会返回.要检查所有元素,您可以尝试这样做:
def detect(list_a,list_b): return set(list_a).issubset(list_b) 其他可能性,无需创建集合: def detect(list_a,list_b): return all(x in list_b for x in list_a) 如果你很好奇你的代码究竟是什么错,那就是当前形式的修复(但它不是非常pythonic): def detect(list_a,list_b): for item in list_a: if item not in list_b: return False # at least one doesn't exist in list_b return True # no element found that doesn't exist in list_b # therefore all exist in list_b 最后,您的函数名称不是很易读.检测太模糊了.考虑其他更冗长的名称,如isSubset等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |