On Thu, Sep 18, 2008 at 03:24:16AM -0700, [EMAIL PROTECTED] wrote: > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. [...] > def findAllMatchingList(mainList, subList): > resultIndex = [] > globalIndex = 0 > for i in range(len(mainList)): > if i < globalIndex: > continue > globalIndex = i > increment = 0 > for j in range(len(subList)): > if mainList[globalIndex] == subList[j]: > globalIndex += 1 > increment += 1 > if j == (len(subList)-1): > resultIndex.append(globalIndex-increment) > else: > break > > return resultIndex
I didn't time them to compare, but how about this instead: >>> def find_needle_in_haystack(needle, haystack): >>> ... r = [] ... L = len(needle) ... for i in range(len(haystack)): ... if haystack[i:i+L] == needle: ... r.append(i) ... return r >>> # this fails because "3" is not 3... >>> >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,"3","9"]) >>> [] >>> find_needle_in_haystack([1,2,3], [1,2,3]) >>> [0] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9"]) >>> [2] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9","q",1,2,3]) >>> [2, 7] -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D
pgpNKYFN6mu45.pgp
Description: PGP signature
-- http://mail.python.org/mailman/listinfo/python-list