3

I am a newbie to python and just learning things as i do my project and here i have two list of list which i need to compare and separate the diff found in A -- > B and diff found b --> A What is the best way of comparing.

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']]
1
  • This isn't a really good data structure to compare efficiently. If you had lists of tuples you could convert one to a set. This small change would allow you to compare in linear time Commented Jun 20, 2012 at 5:33

3 Answers 3

4

Assuming you can use a list of tuples as per my comment, this simple modification of Junuxx's answer is much more efficient

A - B:

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

B - A:

>>> seta = set(A)
>>> [x for x in B if not x in seta]
[(1L, 'test_case_4'), (2L, 'test_case_3')]
Sign up to request clarification or add additional context in comments.

2 Comments

I have seen your other answers too about fast way of computation in Python. Do you have any blog where you keep more of these?
Why not simply seta - setb or setb - seta ?
2

You can do this easily with a list comprehension,

A - B:

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

B - A:

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

Comments

1

Just use List Comprehension

A - B:

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

B - A:

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

A fast way: first can make the B to a set(), then use Generator

For 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>

2 Comments

Have you tried this? set(B) results in TypeError: unhashable type: 'list'.
@Junuxx first should translate the B to tuple of list

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.