Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: find a list within members of another list(in order)

Tags:

python

list

If I have this:

a='abcdefghij'
b='de'

Then this finds b in a:

b in a => True

Is there a way of doing an similar thing with lists? Like this:

a=list('abcdefghij')
b=list('de')

b in a => False 

The 'False' result is understandable - because its rightly looking for an element 'de', rather than (what I happen to want it to do) 'd' followed by 'e'

This is works, I know:

a=['a', 'b', 'c', ['d', 'e'], 'f', 'g', 'h']
b=list('de')
b in a => True

I can crunch the data to get what I want - but is there a short Pythonic way of doing this?

To clarify: I need to preserve ordering here (b=['e','d'], should return False).

And if it helps, what I have is a list of lists: these lists represents all possible paths (a list of visited nodes) from node-1 to node-x in a directed graph: I want to 'factor' out common paths in any longer paths. (So looking for all irreducible 'atomic' paths which constituent all the longer paths).

Related

  • Best Way To Determine if a Sequence is in another sequence in Python
like image 506
monojohnny Avatar asked Feb 12 '10 09:02

monojohnny


2 Answers

I suspect there are more pythonic ways of doing it, but at least it gets the job done:

l=list('abcdefgh')
pat=list('de')

print pat in l # Returns False
print any(l[i:i+len(pat)]==pat for i in xrange(len(l)-len(pat)+1))
like image 131
MAK Avatar answered Nov 01 '22 20:11

MAK


Don't know if this is very pythonic, but I would do it in this way:

def is_sublist(a, b):
    if not a: return True
    if not b: return False
    return b[:len(a)] == a or is_sublist(a, b[1:])

Shorter solution is offered in this discussion, but it suffers from the same problems as solutions with set - it doesn't consider order of elements.

UPDATE:
Inspired by MAK I introduced more concise and clear version of my code.

UPDATE: There are performance concerns about this method, due to list copying in slices. Also, as it is recursive, you can encounter recursion limit for long lists. To eliminate copying, you can use Numpy slices which creates views, not copies. If you encounter performance or recursion limit issues you should use solution without recursion.

like image 27
Rorick Avatar answered Nov 01 '22 20:11

Rorick