Chaining Lists Together In Python With Condition Matching

I have lists of two-word phrases that I need to try to daisy chain together. I have twelve lists with thousands of entries in each list, and I need to find all possible chains. The order of the lists relative to each other is fixed -- list 3 follows, list 2 follows list 1, etc. I have a solution, but it is not very Pythonic and it takes forever to run. My last run took 3 hours and 40 min, which is completely unworkable.

So, I'm looking for any solutions that would be more efficient and (hopefully) speed up the process to something that is manageable.

The input data is formatted as 2D lists, like this:

l1 = [ ['SHORT', 'FILM'], ['LEASE', 'BACK'], ['SHELF', 'LIFE'], ['HOLDS', 'FAST'], ... ]
l2 = [ ['BOAT', 'DECK'], ['FAST', 'FOOD'], ['FILM', 'PROP'], ['CHOW', 'LINE'], ... ]
l3 = [ ['FOOD', 'DRIVE'], ['PROP', 'PLANE'], ['GOAL', 'LINES'], ['WRAP', 'PARTY'], ... ]
l12 = ...

And, I need to find all possible chains of words that match the second word of each pair on a list with the first word on the next list, etc, daisy chaining all the way through.

The code I have (shortened to only three lists for brevity) looks like:

l1 = [['SHORT', 'FILM'], ['LEASE', 'BACK'], ['SHELF', 'LIFE'], ['HOLDS', 'FAST']]
l2 = [['BOAT', 'DECK'], ['FAST', 'FOOD'], ['FILM', 'PROP'], ['CHOW', 'LINE']]
l3 = [['FOOD', 'DRIVE'], ['PROP', 'PLANE'], ['GOAL', 'LINES'], ['WRAP', 'PARTY']]

ans = []

for i in range(len(l1)):
        for j in range(len(l2)):
                if  l1[i][1] == l2[j][0]:
                        for k in range(len(l3)):
                                if l2[j][1] == l3[k][0]:
                                        item = [l1[i][0], l1[i][1], l2[j][1], l3[k][1]]


Which gives the output of::

[['SHORT', 'FILM', 'PROP', 'PLANE'], ['HOLDS', 'FAST', 'FOOD', 'DRIVE']]

Any suggestions on a more efficient and faster(!) way to do this?

Thanks in advance!

Read more here:

Content Attribution

This content was originally published by alkemyst at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: