鱼C论坛

 找回密码
 立即注册
查看: 1414|回复: 1

[技术交流] Python 实现 tabulate()

[复制链接]
发表于 2020-4-8 18:30:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Python 实现 tabulate()


语法

  1. 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。


返回值

生成器。

例子

  1. >>> t = tabulate(lambda x: x ** 2, 1)    # 起始值为 1
  2. >>> for i in range(5):
  3.         print(next(t))

  4.        
  5. 1
  6. 4
  7. 9
  8. 16
  9. 25
  10. >>> t = tabulate(lambda x: x * 2, step=2)    # 步长为 2
  11. >>> for i in range(5):
  12.         print(next(t))

  13.        
  14. 0
  15. 4
  16. 8
  17. 12
  18. 16
复制代码


[b]代码[/b]

  1. def tabulate(func, start: "int or float" = 0, step: "int or float" = 1):
  2.     """无限地返回 func(start), func(start + step), func(start + step * 2) ..."""
  3.     while True:
  4.         yield func(start)
  5.         start += step
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-8 18:43:00 | 显示全部楼层
  1. from itertools import count
  2. tabulate=lambda func,start=0,step=1:(func(i) for i in count(start,step))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 05:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表