How Do You Find Common Sublists Between Two Lists?
How do you find or keep only the sublists of a list if it the sublist is also present within another list? lsta = [['a','b','c'],['c','d','e'],['e','f','g']] lstb = [['a','b','c'],
Solution 1:
Better change the list of lists to list of tuples, then you can easily use the set operations:
>>> tupa = map(tuple, lsta)
>>> tupb = map(tuple, lstb)
>>> set(tupa).intersection(tupb)
set([('a', 'b', 'c'), ('e', 'f', 'g')])
>>> set(tupa).difference(tupb)
set([('c', 'd', 'e')])
Solution 2:
If your sub-lists need to remain lists, use a list comprehension
Intersection:
>>> [i for i in lsta if i in lstb][['a', 'b', 'c'], ['e', 'f', 'g']]
Subtraction:
>>> [i for i in lsta if i not in lstb][['c', 'd', 'e']]
Solution 3:
I have written a C module a while ago for this:
>>> lsta = [['a','b','c'],['c','d','e'],['e','f','g']]
>>> lstb = [['a','b','c'],['d','d','e'],['e','f','g']]
>>> list(boolmerge.andmerge(lsta, lstb))
>>> import boolmerge
[['a', 'b', 'c'], ['e', 'f', 'g']]
This is O(n) time, and require the lists to be sorted.
Post a Comment for "How Do You Find Common Sublists Between Two Lists?"