python 统计两个列表的差异值(python get the different element between the two lists)

 

列表有加法,列表的加法就是列表的拼接。

在列表中,没有减法操作,但有时我们需要计算两个列表的差异值,一般的求列表差异值的方法只能求得不存在重复元素的差异值,但是当元素存在重复现象,那求得的差异值并不是我们真正想要的,现发现了一个高级的求出列表差异值的方法,不仅可以得到差异值元素,还能得到相差的个数,真是妙,分享给大家 ~

 

1. 简单的求列表差异值的2种方法:

参考资料:https://www.delftstack.com/howto/python/python-list-subtraction/

适用场景:不存在重复元素

 

方法一:

In [1]: list1 = [1, 2, 3, 4, 5, 6, 7, 8]

In [2]: list2 = [2, 3, 5, 6, 7]

In [3]: list(set(list1)-set(list2))
Out[3]: [8, 1, 4]

 

方法二:

In [5]: list1 = [1, 2, 3, 4, 5, 6, 7, 8]

In [6]: list2 = [2, 3, 5, 6, 7]

In [7]: [i for i in list1 if not i in list2]
Out[7]: [1, 4, 8]

不适用场景:列表中存在重复元素

In [8]: list1 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

In [9]: list2 = [1, 2, 3, 3, 4, 4, 5]

In [10]: list(set(list1)-set(list2))
Out[10]: []

In [11]: [i for i in list1 if not i in list2]
Out[11]: []

可以看到,这时候无论用哪一种方法都无法得到我们想要的结果,这时候统计2个列表差异值的高级方法出来了。

 

2. 得到2个列表的差异值并给出差异值个数的高级方法

参考资料:https://stackoverflow.com/questions/3428536/python-list-subtraction-operation

 

In [42]: from collections import Counter

In [43]: list1 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

In [44]: list2 = [1, 2, 3, 3, 4, 4, 5]

In [45]: for key, value in (Counter(list1)-Counter(list2)).items():
    ...:     print("key = ", key, "value = ", value)
    ...:
key =  2 value =  1
key =  3 value =  1
key =  4 value =  2
key =  5 value =  4

In [46]: list((Counter(list1) - Counter(list2)).elements())
Out[46]: [2, 3, 4, 4, 5, 5, 5, 5]

 注意,在用这个方法求差值的时候不同的减数和被减数得到的结果是不同的,要根据具体需要赋值。

 

posted @ 2021-05-27 17:58  ttweixiao9999  阅读(483)  评论(0编辑  收藏  举报