首页 > 编程 > Python > 正文

Python 内建模块 itertools

2019-11-08 01:16:03
字体:
来源:转载
供稿:网友

count() 会创建一个无限的迭代器

“` import itertools ns = itertools.count(1) for n in ns: PRint(ns)

但是可以通过takewhile()打印一个有限序列

nu = itertools.count(1) ns = itertools.takewhile(lambda x: x <= 10, nu) list(ns) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.cycle() 重复循环打印字符串

ns = itertools.cycle(‘abx’) for n in ns: print(ns)

3.repeat() 可以控制打印的次数

ns = itertools.repeat(‘abc’,3) for n in ns: print(ns)

4.chain() 可以把多个**迭代对象**连接起来,构成一个迭代器:

for c in itertools.chain(‘ABC’, ‘XYZ’): print(c)

迭代效果:’A’ ‘B’ ‘C’ ‘X’ ‘Y’ ‘Z’

5.groupby() 把迭代器中相邻的重复元素跳出来放到一起

for key,group itertools.chain(‘aaafferrrty’): print(key,list(group) “`

感觉好无聊的,不知道在哪呀,希望用的时候可以想起来


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表