Rita Sue and Bob too

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Fri Aug 20 15:41:41 CEST 2004


In article <cg3ksb$bg5$1 at newsg2.svr.pol.co.uk>,
 "M. Clift" <noone at here.com> wrote:

> Hi All,
> 
> Can someone help. I promise I've looked how to do this but can't find a
> way...
> 
> Ok, to find one name is easy
> 
> if 'Bob' in list:
>     print "They were found"
> else:
>     print "They are not in list"
> 
> But, how to I find a sequence in a list of unknown size? i.e. this sequence
> in list of other names and replace it with three others?
> 
> 'Rita','Sue','Bob'
> 
> This is almost a nightly occurrence (my posting questions), but I am
> learning : )

You've gotten several other answers, but I'd like to propose yet another 
one:

  def replace_sublist(L, S, T):
      """Replace each sublist of L equal to S with T.  Also returns the 
      resulting list."""
      
      assert(len(S) == len(T))
      
      for p in [ x for x in xrange(len(L))
                 if L[x] == S[0] and L[x : x + len(S)] == S ]:
          L[p : p + len(S)] = T
      
      return L

In short, the list comprehension gives all the offsets in L where a copy 
of S can be found as a sublist.  Now, if it happens that some of these 
positions overlap (e.g., L = [ 1, 1, 1 ] and S = [ 1, 1 ]), then the 
results will be strange.  But as long as your matches do not overlap, 
this should work well.

-M

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list