3

我是 python 的新手,只是在做我的项目时学习东西,这里我有两个列表列表,我需要比较和分离在 A --> B 中找到的差异和在 b --> A 中找到的差异最好的比较方式。

A=[[1L, 'test_case_1'], [1L, 'test_case_2'], [2L, 'test_case_1']]
B=[[1L, 'test_case_1'], [1L, 'test_case_4'], [2L, 'test_case_1'], [2L, 'test_case_3']]
4

3 回答 3

4

假设您可以按照我的评论使用元组列表,那么对 Junuxx 答案的简单修改会更有效

甲 - 乙:

>>> setb = set(B)
>>> [x for x in A if not x in setb]
[(1L, 'test_case_2')]

乙 - 甲:

>>> seta = set(A)
>>> [x for x in B if not x in seta]
[(1L, 'test_case_4'), (2L, 'test_case_3')]
于 2012-06-20T05:36:59.513 回答
2

您可以通过列表理解轻松完成此操作,

甲 - 乙:

>>> [x for x in A if not x in B]
[[1L, 'test_case_2']]

乙 - 甲:

>>> [x for x in B if not x in A]
[[1L, 'test_case_4'], [2L, 'test_case_3']]
于 2012-06-20T05:09:32.257 回答
1

只需使用列表理解

甲 - 乙:

>>>[p for p in A if p not in B]
[[1L, 'test_case_2']]

乙 - 甲:

>>>[p for p in B if p not in A]
[(1L, 'test_case_4'), (2L, 'test_case_3')]

一个快速的方法:首先可以制作Bto a set(),然后使用Generator

对于A - B:

>>>B = [(l[0], l[1]) for l in B]
>>>set_b = set(B)
>>>(p for p in A if p not in set_b)
<generator object <genexpr> at 0x00BCBBE8>
于 2012-06-20T05:46:23.007 回答