append to items depending on prior item

Alex Martelli aleaxit at yahoo.com
Sun Oct 3 13:13:26 EDT 2004


M. Clift <noone at here.com> wrote:
   ...
> What I have is a say item1, item4, item2, item1 etc...
> 
> What I want to do is append to each item an extra value depending on the
> previous item.
> 
> from random import *
> 
> items = [' item1',' item4',' item2',' item1']
> 
> items[0].append choice('1','2','3')
> print items
> 
> for idx in range(len(items)):
>     if previous item == ['item1']:
>         next item.append choice('a','b','c')
>     if previous item == ['item2']:
>         next item.append choice('d','e','f')
> 
>         print items
> 
> appended items = item1b, item4a, item2f etc...

This latest example totally contrast with everything else you're saying.
How could 'b' get appended to the first 'item1', for example, when
you're trying to use a choice among '1', '2' and '3'?!  I'm going to try
to guess what you mean (if you had been a bit more precise in your
example of desired input and output it WOULD have been far better, of
course)...:

def weird_appender(sequence):
    choices = dict({None: '123'}, item1='abc', item2='def')
    previous = None
    for item in sequence:
        yield item+random.choice(choices.get(previous, choices[None]))
        previous = item

and if for some super=weird reason you want to trample the contents of
list items rather than just operating on a sequence-in / sequence-out
basis, items[:]=weird_appender(items) will serve.


Alex



More information about the Python-list mailing list