列表迭代替换为单行

List iteration with substitution into one-liner

我想打开以下 for 循环:

n = 10
x0 = 0
values = [x0]
for i in range(n):
    x0 = f(x0)
    values.append(x0)

变成一个班轮。我想我可以做这样的事情:

values = [f(x0) for i in range(n)]

但我需要在每个循环实例中更新 x0 的值。有什么想法吗?

Walrus operator := 救援:

>>> x0 = 0
>>> def f(x): return x*2 + 1
... 
>>> [x0:=f(x0) for _ in range(10)]
[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
>>> x0
1023 # x0 was modified

除了海象,more_itertools还有一个函数iterate可以重复应用:

import more_itertools as mo

mo.take(10, mo.iterate(f, x0))