Home > Software engineering >  Python: Markov Iteration over list in one line
Python: Markov Iteration over list in one line

Time:01-18

when I create a list, I use the one-liner

[fct(item) for item in somelist]

Is there a simple way to write the following iteration in one line?

new_list = [0]
for _ in range(N)
    new_list.append(fct(new_list[-1]))

or even

new_list = [0]
for t in range(N)
    new_list.append(fct(t,new_list[-1]))

CodePudding user response:

You can use an assignment expression to store the returning value of the last call to fct, but since you also want the initial value 0 to be in the list, you would have to join it separately:

new_list = [i := 0]   [i := fct(i) for _ in range(N)]

or even:

new_list = [i := 0]   [i := fct(t, i) for t in range(N)]

CodePudding user response:

itertools.accumulate() exists exactly for that:

from itertools import accumulate
list(accumulate(range(N), fnc)) # == [0, fnc(0,1), fnc(fnc(0,1),2),..]

If you wish to dump the N, just use accumulate like so:

from itertools import accumulate
list(accumulate(range(N), lambda x, y: fnc(x))) # == [0, fnc(0), fnc(fnc(0)),..]
  • Related