pythonic-迭代器函数-itertools
认识
Python 的itertools模块提供了很多节省内存的高效迭代器, 尤其解决了一些关于数据量太大而导致内存溢出(outofmemory)的场景.
我们平时用的循环绝大多数是这样的.
# while 循环: 求1+2+...100
s, i = 0, 1
while i <= 100:
s += i
i += 1
print('while-loop: the some of 1+2+..100 is:', s)
# for 循环
s = 0
for i in range(101):
s += i
print('for-loop: the some of 1+2+..100 is:', s)
while-loop: the some of 1+2+..100 is: 5050
for-loop: the some of 1+2+..100 is: 5050
但如果数据量特别大的话就凉凉了, 所以引入了itertools,迭代器, 类似于懒加载的思想
常用API
- chain()
- groupby()
- accumulate()
- compress()
- takewhile()
- islice()
- repeat()
chain 拼接元素
- 把一组迭代对象串联起来,形成一个更大的迭代器:
# join / split
s = "If you please draw me a sheep?"
s1 = s.split()
s2 = "-".join(s1)
print("split->:", s1)
print("join->:", s2)
split->: ['If', 'you', 'please', 'draw', 'me', 'a', 'sheep?']
join->: If-you-please-draw-me-a-sheep?
import itertools
# chain
s = itertools.chain(['if', 'you'], ['please draw', 'me', 'a'], 'shape')
s
<itertools.chain at 0x1d883602240>
list(s)
['if', 'you', 'please draw', 'me', 'a', 's', 'h', 'a', 'p', 'e']
不难发现, 这就是迭代器嘛, 真的没啥.跟join差不多. 那么它是如何节省内存的呢, 其实就是一个简单的迭代器思想, 一次读取一个元素进内存,这样就高效节约内存了呀
def chain(*iterables):
for iter_ in iterables:
for elem in iter_:
yield elem
groupby 相邻元素
- 把迭代器中相邻的重复元素挑出来放在一
# 只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,而函数返回值作为组的key
for key, group in itertools.groupby('AAABBBCCAAAdde'):
print(key, list(group))
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
d ['d', 'd']
e ['e']
# 忽略大小写
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(key, list(group))
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
accumulate 累积汇总
list(itertools.accumulate([1,2,3,4,5], lambda x,y: x*y))
[1, 2, 6, 24, 120]
# 伪代码
def accumulate(iterable, func=None, *, initial=None):
iter_ = iter(iterable)
ret = initial
# 循环迭代
if initial is None:
try:
ret = next(iter_)
except StopIteration:
return
yield ret
# 遍历每个元素, 调用传入的函数去处理
for elem in iter_:
ret = func(elem)
yield ret
compress 过滤
list(itertools.compress('youge', [1,0,True,3]))
['y', 'u', 'g']
def compress(data, selectors):
for d, s in zip(data, selectors):
if s:
return d
# demo
for data, key in zip([1,2], 'abcd'):
print(data,key)
if key:
print(data)
1 a
1
2 b
2
# Pythonic
def compress(data, selectors):
return (d for d, s in zip(data, selectors) if s)
# tset
ret = compress(['love', 'you', 'forever'], ['love', None, 'dd', 'forever'])
print(ret)
print(list(ret))
<generator object compress.<locals>.<genexpr> at 0x000001D8831498E0>
['love', 'forever']
生成器
- 在类中实现了iter()方法和next()方法的对象即生成器
- 代码上有两种形式: 元组生成器 或者 函数中出现 yield 关键字
zip
- 对应位置进行元素拼接, 当最短的匹配上了, 则停止, 也被称为"拉长函数"
take-while
- takewhile: 依次迭代, 满足条件则返回, 继续迭代, 一旦不满足条件则退出
# takewhile
s1 = list(itertools.takewhile(lambda x:x<=2, [0,3,2,1,-1,3,0]))
print(s1)
s2 = list(itertools.takewhile(lambda x:x<5, [1,4,6,4,1,3]))
print(s2)
# dropwhile
s3 = list(itertools.filterfalse(lambda x:x%2==0, range(10)))
print(s3)
[0]
[1, 4]
[1, 3, 5, 7, 9]
def take_while(condition, iter_obj):
for elem in iter_obj:
if conditon(elem):
yield elem
else:
break
dropwhile: 不满足条件的则返回
islice 切片
# 普通的切片,也是要先全部读入内存
# 注意是深拷贝的哦
l = [1,2,3,4,5]
print(l[::--1])
# generator 方式
# 默认的 start, stop, step, 只能传0或正数, 但可以自己改写的呀
list(itertools.islice(l, 0,3,1))
s = slice(3,4,5) # 只接收3个参数
s.start
s.stop
[1, 2, 3, 4, 5]
[1, 2, 3]
3
4
import sys
def slice(iter_obj, *args):
s = slice(*args)
start = s.start or 0
stop = s.stop or sys.maxsize # 很大的常量
step = s.step or 1
# 构成可迭代的对象(下标)
iter_ = iter(range(start, stop, step))
try:
next_i = next(iter_)
except StopIteration:
# for i, elem n zip(range(start), iter_obj):
pass
return
try:
i, elem in enumerate(iter_obj):
if i == next_i:
yield elem
next_i = next(elem)
except StopIteration:
pass
[1, 2, 3, 4, 5]
repeat
list(itertools.repeat(['youge'], 3))
[['youge'], ['youge'], ['youge']]
def repeat(obj, times=None):
if times is None:
while True: # 一直返回
yield obj
else:
for i in range(times):
yield obj
pythonic-迭代器函数-itertools的更多相关文章
- Python3标准库:itertools迭代器函数
1. itertools迭代器函数 itertools包括一组用于处理序列数据集的函数.这个模块提供的函数是受函数式编程语言(如Clojure.Haskell.APL和SML)中类似特性的启发.其目的 ...
- 这段代码很Pythonic | 相见恨晚的 itertools 库
前言 最近事情不是很多,想写一些技术文章分享给大家,同时也对自己一段时间来碎片化接受的知识进行一下梳理,所谓写清楚才能说清楚,说清楚才能想清楚,就是这个道理了. 很多人都致力于把Python代码写得更 ...
- python迭代器以及itertools模块
迭代器 在python中,迭代器协议就是实现对象的__iter()方法和next()方法,其中前者返回对象本身,后者返回容器的下一个元素.实现了这两个方法的对象就是可迭代对象.迭代器是有惰性的,只有在 ...
- 迭代器模块 itertools
无限迭代器 itertools 包自带了三个可以无限迭代的迭代器.这意味着,当你使用他们时,你要知道你需要的到底是最终会停止的迭代器,还是需要无限地迭代下去. 这些无限迭代器在生成数字或者在长度未知的 ...
- python基础===Python 迭代器模块 itertools 简介
本文转自:http://python.jobbole.com/85321/ Python提供了一个非常棒的模块用于创建自定义的迭代器,这个模块就是 itertools.itertools 提供的工具相 ...
- CodeForces 670E Correct Bracket Sequence Editor(list和迭代器函数模拟)
E. Correct Bracket Sequence Editor time limit per test 2 seconds memory limit per test 256 megabytes ...
- Python迭代器包itertools(转)
原文:http://www.cnblogs.com/vamei/p/3174796.html 作者:Vamei 在循环对象和函数对象中,我们了解了循环器(iterator)的功能.循环器是对象的容器, ...
- Python迭代器(函数名的应用,新版格式化输出)
1. 函数名的运用 你们说一下,按照你们的理解,函数名是什么? 函数名的定义和变量的定义几乎一致,在变量的角度,函数名其实就是一个变量,具有变量的功能:可以赋值:但是作为函数名他也有特殊的功能 ...
- Python标准库:迭代器Itertools
Infinite Iterators: Iterator Arguments Results Example count() start, [step] start, start+step, star ...
随机推荐
- 原始js---JavaScript注册用正则验证用户名密码手机号邮箱验证码
注册文件 reg.html <html><style> #btn{ background-color: red; color:white; width: 235px; } sp ...
- webpack中路径的理解
webpack 前端打包工具, 开发人员要面对的路径主要是: 打包前的路径(开发环境路径)和打包后的路径(生产环境路径) 在webpack.config.js中配置的output.path, outp ...
- Sublime Text3 设置
主题:Spacegrey.sublime-theme 配色方案:Mariana 自动保存 参考:https://www.cnblogs.com/mzzz/p/6178341.html "sa ...
- 优先队列优化的 Huffman树 建立
如果用vector实现,在运行时遍历寻找最小的两个节点,时间复杂度为O(N^2) 但是我们可以用priority_queue优化,达到O(N logN)的时间复杂度 需要注意的是priority_qu ...
- springcloud的Hystrix turbine断路器聚合监控实现(基于springboot2.02版本)
本文基于方志朋先生的博客实现:https://blog.csdn.net/forezp/article/details/70233227 一.准本工作 1.工具:Idea,JDK1.8,Maven3. ...
- Comet OJ - Contest #1 C 复读游戏(状态压缩)
题意 https://www.cometoj.com/contest/35/problem/C?problem_id=1498 思路 这题要用到一种比较小众的状压方法(没见过的话可能一时比较难想到). ...
- 解决docker容器日志导致主机磁盘空间满了的情况
日志文件在 /var/lib/docker/containers/<docker_container_id>/ 目录下 查看日志大小 vim /opt/docker_log_siz ...
- 不让应用的日志输出到message文件中
有时我们制定一个应用的日志输出到一个文件的时候例如: (百度了好久都百度不好,这里记录一下时间2015年12月7日16:28:39) local7.* ...
- 红米note7几个问题处理
1.听筒声音很小,外放正常,试了很多种方法,最终可行的是吧听筒网灰尘弄一下. 2.SAICLink车机互联:需要打开USB调试.USB安装.USB调试(安全设置)(不开启这个的话会连接后就断开).默认 ...
- Springboot Actuator之七:actuator 中原生endpoint源码解析1
看actuator项目的包结构,如下: 本文中的介绍Endpoints. Endpoints(端点)介绍 Endpoints 是 Actuator 的核心部分,它用来监视应用程序及交互,spring- ...