2012-06-20 80 views
2

我是一个Python新手,刚刚学习的东西,因为我做我的项目,在这里我有两个列表,我需要比较和分开在A - > B和diff发现b - > A 比较的最佳方法是什么?在Python中有效比较列表的两个列表

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']] 
+0

这并不是一个非常好的数据结构来进行有效比较。如果你有*元组清单*,你可以将其转换为一个集合。这个小小的变化可以让你在线性时间内进行比较 –

回答

4

假设你可以使用列表元组根据我的评论,这个Junuxx的答案的简单修改是更多的e fficient

A - B:

>>> 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')] 
+0

我也看到了你的其他答案,关于Python的快速计算方法。你有没有更多的这些博客? – codecool

+0

@codecool,对不起没有博客。也许我应该开始一个 –

+0

你应该做一个! :) – codecool

2

你可以用一个列表理解这样做很容易,

A - B:

>>> [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']] 
0

只需使用List Comprehension

A - B:

>>>[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')] 

的一个快速方法:首先可以使Bset(),然后用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> 
+0

你有试过吗? 'set(B)'导致'TypeError:不可用类型:'list''。 – Junuxx

+0

@Junuxx首先应该把'B'转换成''元组列表' – shihongzhi