您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

基本上,您希望将一个元素添加到新列表中(如果一个元素存在而另一个元素中不存在)。这是一个可以做到的紧凑循环。对于两个列表中的每个元素(将它们与相连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
其他 2022/1/1 18:51:26 有428人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶