比较两个无序列表以了解各个元素的差异

时间:2019-04-09 13:12:13

标签: 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)

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

从评论看来,您似乎想在计算差异之前先“解压”嵌套的伪字符串列表。您可以为此定义一个简单的辅助函数。

>>> listA = ['A' , 'B' , 'C, D' , 'E, F, G', 'H' , 'I']
>>> listB = ['C' , 'E, G' , 'A' , 'B' , 'I']
>>> elements = lambda s: set(x for y in s for x in y.split(", "))
>>> elements(listA)
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}

然后,您可以使用set-^&之类的|操作来获取所需的内容。

>>> elements(listA) - elements(listB) # difference
{'D', 'F', 'H'}
>>> elements(listA) ^ elements(listB) # sym. diff.
{'D', 'F', 'H'}
>>> elements(listA) & elements(listB) # intersection
{'A', 'B', 'C', 'E', 'G', 'I'}
>>> elements(listA) | elements(listB) # union
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}

答案 2 :(得分:1)

交集是集合的常见部分。如果您想要套组不同,请使用...一种套用方法。 例如:

list(set(listA) - set(listB))

或:

list(set(listA).difference(set(listB)))

答案 3 :(得分:1)

listA = ['E','F','G']
listB = ['E','G']

使用列表理解

diff2 = [y for y in listA if y not in listB]
print (diff2)

输出:['F']

diff1=[]
for item in listA:
    if item not in listB:
        diff1.append(item)
print (diff1)

输出:['F']