【发布时间】:2012-09-08 06:07:08
【问题描述】:
例如: NestList(f,x,3) ----> [x, f(x), f(f(x)), f(f(f(x)))]
【问题讨论】:
标签: python list function iterator
例如: NestList(f,x,3) ----> [x, f(x), f(f(x)), f(f(f(x)))]
【问题讨论】:
标签: python list function iterator
使用functional 模块。它有一个名为scanl 的函数,它产生一个减少的每个阶段。然后,您可以减少 f 的实例列表。
【讨论】:
it=functional.iterate(lambda x: 2*x-1,2) print [it.next() for i in range(11)]
itertools 中的实用程序,以执行诸如从迭代器 (itertools.islice) 中获取切片等操作。
def nest_list(f, x, i):
if i == 0:
return [x]
return [x] + nest_list(f, f(x), i-1)
def nest_list(f, x, n):
return [reduce(lambda x,y: f(x), range(i), x) for i in range(n+1)]
我找到了另一种方法!
【讨论】:
list(accumulate(repeat(x, n), lambda x,y: f(x))),使用来自 itertools 模块的 accumulate 和 repeat。
你可以把它写成一个生成器:
def nestList(f,x,c):
for i in range(c):
yield x
x = f(x)
yield x
import math
print list(nestList(math.cos, 1.0, 10))
或者如果你想将结果作为一个列表,你可以在一个循环中追加:
def nestList(f,x,c):
result = [x]
for i in range(c):
x = f(x)
result.append(x)
return result
import math
print nestList(math.cos, 1.0, 10)
【讨论】:
nestList(f,x,c) 与 [x] + nestList(f,f(x),c-1) 相同。