python - 比较两个无序列表中单个元素的差异
问题描述
给定两个列表:
listA = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
listB = ['C' , 'E, G' , 'A' , 'B' , 'I']
我想比较每个元素并突出它适用的差异。
listA['E,F,G'] and listB['E,G'].
The difference would be ['F']
各个列表元素之间存在一些差异,理想情况下希望将它们全部标记出来。这可以用python吗?下面的想法正确吗?
set(listA).intersection(listB)
解决方案
您正在寻找的是对称差异。在 python 中,您可以通过使用symmetric_difference
函数或使用简写来实现它s ^ t
。
s.symmetric_difference(t)
这将为您提供不同的元素。现在,你能做的是
def split_words(element):
if len(element) > 1:
element = element.split(',')
return element
result = []
for e1, e2 in zip(sorted(list_a), sorted(list_b)):
if e1 not in list_b:
e1 = split_words(e1)
e2 = split_words(e2)
diff = set(e1) ^ set(e2)
result.append(diff)
推荐阅读
- java - 如何比较具有不同顺序元素的Json数组
- excel - 从另一个嵌套类内部访问一个嵌套类
- c# - 将子类集合转换为父类列表
- java - 上下文元素 'annotation-config' ....在 JDK 1.5 及更高版本上可用
- dhtmlx - DHTMLX 调度程序自定义时间线与 AM/PM 天
- python - TypeError: 'str' 对象不能被解释为整数,即使我给它分配了 int(value)
- python - 在公司内网 0.0.0.0:80 上运行烧瓶的快速方法
- ios - 为什么 Swift Array contains(_:) 方法必须是非可选的时才接受 nil 参数?
- nvidia - NVIDIA Tesla V100 到 Ubuntu 18.04 LTS 或 Centos 来宾的 Windows Server 2019 Hyper-V 离散设备分配 (DDA):未找到
- javascript - 通过单击突出显示一个单词