5

我有两个这样的列表

found = ['CG', 'E6', 'E1', 'E2', 'E4', 'L2', 'E7', 'E5', 'L1', 'E2BS', 'E2BS', 'E2BS', 'E2', 'E1^E4', 'E5']
expected = ['E1', 'E2', 'E4', 'E1^E4', 'E6', 'E7', 'L1', 'L2', 'CG', 'E2BS', 'E3']

我想找出两个列表之间的差异。
我已经做好了

list(set(expected)-set(found))

list(set(found)-set(expected))

分别返回['E3']['E5']

但是,我需要的答案是:

'E3' is missing from found.
'E5' is missing from expected.
There are 2 copies of 'E5' in found.
There are 3 copies of 'E2BS' in found.
There are 2 copies of 'E2' in found.

欢迎任何帮助/建议!

4

3 回答 3

8

collections.Counter类将擅长枚举多集之间的差异:

>>> from collections import Counter
>>> found = Counter(['CG', 'E6', 'E1', 'E2', 'E4', 'L2', 'E7', 'E5', 'L1', 'E2BS', 'E2BS', 'E2BS', 'E2', 'E1^E4', 'E5'])
>>> expected = Counter(['E1', 'E2', 'E4', 'E1^E4', 'E6', 'E7', 'L1', 'L2', 'CG', 'E2BS', 'E3'])
>>> list((found - expected).elements())
['E2', 'E2BS', 'E2BS', 'E5', 'E5']
>>> list((expected - found).elements())

您可能还对difflib.Differ感兴趣:

>>> from difflib import Differ
>>> found = ['CG', 'E6', 'E1', 'E2', 'E4', 'L2', 'E7', 'E5', 'L1', 'E2BS', 'E2BS', 'E2BS', 'E2', 'E1^E4', 'E5']
>>> expected = ['E1', 'E2', 'E4', 'E1^E4', 'E6', 'E7', 'L1', 'L2', 'CG', 'E2BS', 'E3']
>>> for d in Differ().compare(expected, found):
...     print(d)

+ CG
+ E6
  E1
  E2
  E4
+ L2
+ E7
+ E5
+ L1
+ E2BS
+ E2BS
+ E2BS
+ E2
  E1^E4
+ E5
- E6
- E7
- L1
- L2
- CG
- E2BS
- E3
于 2013-04-21T03:19:38.917 回答
4

利用 PythonsetCounter而不是滚动您自己的解决方案:

  1. symmetric_difference: 查找要么在一个集合中,要么在另一个集合中的元素,但不能同时在这两个集合中。
  2. intersection: 找到两个集合共有的元素。
  3. difference:这本质上是您通过从另一组中减去一组来完成的

代码示例

  • found.difference(expected) # set(['E5'])
    
  • expected.difference(found) # set(['E3'])
    
  • found.symmetric_difference(expected) # set(['E5', 'E3'])
    
  • 查找对象的副本:此问题已被引用。使用该技术可以获得所有重复项,并使用生成的Counter对象,您可以找到多少个重复项。例如:

    collections.Counter(found)['E5'] # 2
    
于 2013-04-21T03:01:01.390 回答
2

您已经回答了前两个:

print('{0} missing from found'.format(list(set(expected) - set(found)))
print('{0} missing from expected'.format(list(set(found) - set(expected)))

后两个要求你看看计算列表中的重复项,网上有很多解决方案(包括这个:Find and list duplicates in a list?)。

于 2013-04-21T02:59:34.687 回答