append to items depending on prior item

Peter Otten __peter__ at web.de
Sun Oct 3 14:29:16 EDT 2004


M. Clift wrote:

> Thankyou, it looks perfect. At the risk of sounding dumb, however, what do
> I print to get your output?

You would print all the stuff inside [], i. e.

result = [i + random.choice(dict(item1="abc", item2="def").get(p, [""])) 
    for (p, i) in zip(items[-1:]+items[:-1], items)]
print result

but: the code was *not* meant to be perfect - rather as close as you can get
to obfuscation in Python. 
You should first describe exactly what you want in terms of input/output.
Stating a problem precisely is often the hardest and largest part of its
solution. After that try to write a script as _simple_ and _clear_ as you
can (in Python as opposed to your pseudocode).
If you then ask on c.l.py for help with a specific problem you encounter or
for possible improvements, you'll end up with an idiomatic and
understandable solution which is not necessarily the shortest.
In short: short != good.

More practially: 
- a plain old for-loop (like in Alex Martelli's post) with a variable to
remember the previous item beats my zip() magic in efficiency and - more
importantly - in clarity.
- if you encounter a long list of if ... elif ... statements, this can often
be simplified into a dictionary lookup.

HTH ...really,
Peter





More information about the Python-list mailing list