栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

比较两个列表,仅打印差异?(对两个列表进行异或)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

比较两个列表,仅打印差异?(对两个列表进行异或)

基本上,您希望将一个元素添加到新列表中(如果一个元素存在而另一个元素中不存在)。这是一个可以做到的紧凑循环。对于两个列表中的每个元素(将它们与相连

list1+list2
),如果其中一个元素中不存在该元素,我们将添加该元素:

[a for a in list1+list2 if (a not in list1) or (a not in list2)]

您可以像现在一样,通过显式遍历元素轻松地将其转换为更非Python的代码,但是老实说,我看不到要点(不是很重要):

def xor(list1, list2):    outputlist = []    list3 = list1 + list2    for i in range(0, len(list3)):        if ((list3[i] not in list1) or (list3[i] not in list2)) and (list3[i] not in outputlist):  outputlist[len(outputlist):] = [list3[i]]    return outputlist


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号