首页 > 解决方案 > 比较两个无序列表中单个元素的差异

问题描述

给定两个列表:

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

解决方案


您正在寻找的是对称差异。在 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)

推荐阅读