Python 实现 tabulate()
Python 实现 tabulate()语法
tabulate(func, start=0, step=1)
描述
该函数返回一个生成器,生成器会返回 func(start),func(start + step),func(start + step * 2),func(start + step * 3),…… 的结果。
参数
参数描述
func一个函数。
start起始值,默认为 0,只能是 int 或 float。
step步长,默认为 1,只能是 int 或 float。
返回值
生成器。
例子
>>> t = tabulate(lambda x: x ** 2, 1) # 起始值为 1
>>> for i in range(5):
print(next(t))
1
4
9
16
25
>>> t = tabulate(lambda x: x * 2, step=2) # 步长为 2
>>> for i in range(5):
print(next(t))
0
4
8
12
16
代码
def tabulate(func, start: "int or float" = 0, step: "int or float" = 1):
"""无限地返回 func(start), func(start + step), func(start + step * 2) ..."""
while True:
yield func(start)
start += step from itertools import count
tabulate=lambda func,start=0,step=1:(func(i) for i in count(start,step))
页:
[1]