Search a list of list of strings for a list of strings in python efficiently
Question: I have a list of list of strings and a list of strings. for example:

    
    
    L1=[["cat","dog","apple"],["orange","green","red"]]
    L2=["cat","red"]
    

if L1[i] contains any item from L2 I need to put the pairs (for creating edges
in a graph) like, in my example, I need the pairs
`("cat","dog"),("cat,apple"),("red,orange"),("red","green")`

What approach should I use to make it most efficient. (My list L1 is huge)


Answer: Supposing that you might have, more than one "control" item in your L1
sublists.

I'd do it using
[`set()`](http://docs.python.org/py3k/library/stdtypes.html#set-types-set-
frozenset) and
[`itertools.product()`](http://docs.python.org/py3k/library/itertools.html#itertools.product):

    
    
    from itertools import product
    
    def generate_edges(iterable, control):
        edges = []
        control_set = set(control)
        for e in iterable:
            e_set = set(e)
            common = e_set & control_set
            to_pair = e_set - common
            edges.extend(product(to_pair, common))
        return edges
    

Example:

    
    
    >>> L1 = [["cat","dog","apple"],
    ...       ["orange","green","red"],
    ...       ["hand","cat","red"]]
    >>> L2 = ["cat","red"]
    >>> generate_edges(L1, L2)
    [('apple', 'cat'),
     ('dog', 'cat'),
     ('orange', 'red'),
     ('green', 'red'),
     ('hand', 'red'),
     ('hand', 'cat')]
    

