在python中:两个列表之间的区别

2024-05-28 21:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张这样的单子

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.

欢迎任何帮助/建议!


Tags: ofincgareexpectedtheresetcopies
3条回答

利用Python ^{} class^{} class而不是滚动您自己的解决方案:

  1. symmetric_difference:查找一个集合或另一个集合中的元素,但不能同时查找这两个集合中的元素。
  2. intersection:查找与这两组元素相同的元素。
  3. difference:本质上就是从一个集合减去另一个集合

代码示例

  • found.difference(expected) # set(['E5'])
    
  • expected.difference(found) # set(['E3'])
    
  • found.symmetric_difference(expected) # set(['E5', 'E3'])
    
  • 正在查找对象的副本:this question已被引用。使用该技术可以获得所有重复项,并使用结果Counter对象,可以找到多少重复项。例如:

    collections.Counter(found)['E5'] # 2
    

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

你已经回答了前两个问题:

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?)。

相关问题 更多 >

    热门问题