A ListComp that maintains its own state
Bernhard Herzog
bh at intevation.de
Wed Feb 9 05:30:38 EST 2005
Michael Spencer <mahs at telcopartners.com> writes:
> So, here's factorial in one line:
> # state refers to list of state history - it is initialized to [1]
> # on any iteration, the previous state is in state[-1]
> # the expression also uses the trick of list.append() => None
> # to both update the state, and return the last state
>
> >>> [state.append(state[-1] * symbol) or state[-1]
> ... for symbol, state in it.izip(range(1,10),it.repeat([1]))
> ... ]
> [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
> >>>
There's no need for repeat:
>>> [state.append(state[-1] * symbol) or state[-1]
for state in [[1]]
for symbol in range(1, 10)]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
While we're at it, a while back I posted a list comprehension that
implements a 'recursive' flatten:
http://groups.google.de/groups?selm=s9zy8eyzcnl.fsf%40salmakis.intevation.de
Bernhard
--
Intevation GmbH http://intevation.de/
Skencil http://skencil.org/
Thuban http://thuban.intevation.org/
More information about the Python-list
mailing list