IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> itertools库常用高效迭代器一览表,帮你快速实现数据的排列组合【python】 -> 正文阅读

[Python知识库]itertools库常用高效迭代器一览表,帮你快速实现数据的排列组合【python】

itertools库常用高效迭代器一览表,帮你快速实现数据的排列组合


文档: https://docs.python.org/zh-cn/3/library/itertools.html

itertools提供一系列的快速、内存高效的iterator,这些迭代器本身或者组合都非常有用。如可以快速获得列表元素的排列、组合结果等。
这些内置工具同时也能很好地与 operator 模块中的高效函数配合使用。
注意:itertools中方法返回(yield)的都是生成器对象,每次调用值处理一个元素,所以是内存高效的。

例如,我们可以将两个向量的点积映射到乘法运算符: sum(map(operator.mul, vector1, vector2))

itertools提供了基本的常用的迭代器,如果感觉不够用,还可以安装 more-itertools 库使用其他迭代器:https://github.com/more-itertools/more-itertools

下面只给出各种迭代器的基本描述和代码示例,供查找使用,函数的详细使用方法务必参考Python官方文档。


itertools中生成的迭代器可以分为多类,如:无限长迭代器有限长迭代器排列组合迭代器

无限长迭代器:

无限长迭代器可以持续使用next()/__next__()方法获取其中的元素。

迭代器描述运算规则示例
count(start[,step])从参数start开始以step为步长,向后生成无限长的数据start, start+ step,start+ 2*stepcount(10)→10,11,12,13…
cycle§p是一个可迭代对象,对p首尾相接生成类似环形的无限长数据p0,p1,…pn,p0,p1,…pn,p0,…cycle(‘ABCD’)→A,B,C,D,A,B,C,D,A,B,C,D…
repeat(elem[,n])重复传入的elem对象无限次或n次elem,elem,elem,…重复无限次或n次repeat(10,3) →10, 10, 10

有限长迭代器:

有限长迭代器的长度取决于传入参数中可迭代对象中最短的一个迭代器的长度。

迭代器描述运算规则示例
accumulate(p[,func])累加器p0,p0+p1,p0+p1+p2,…accumulate([1,2,3,4,5])→1, 3, 6, 10, 15
chain(p,q,…)链式连接器p0,p1,…,pn,q0,q1,…,qnchain(‘ABC’, ‘DEF’) →A,B,C,D,E,F
chain.from_iterable(iterable)可迭代对象元素的链式连接器p0,p1,…,pn,q0,q1,…,qn,…(p,q是iterable中的元素)chain.from_iterable([‘ABC’, ‘DEF’]) →A,B,C,D,E,F
compress(data, selectors)根据selectors中元素的True/False, 从data中挑选对应元素(d[0] if s[0]), (d[1] if s[1]), …compress(‘ABCDEF’, [1,0,1,0,1,1]) →A C E F
dropwhile(pred_func, seq)从pred_func第一次返回False开始,输出seq中后面的元素(即,当开始pred_func返回True时,丢弃数据)seq[n], seq[n+1],…其中seq[n]是第一个使得pred_func返回False的元素dropwhile(lambda x: x < 10, [3, 5, 7, 9, 10, 9, 19, 8, 45, 3]) →10, 9, 19, 8, 45, 3
filterfalse(pred_func, seq)返回seq中使得pred_func为False的元素seq[n] if pred_func(seq[n]) == Falsefilterfalse(lambda x: x%2, range(10)) →0,2,4,6,8
?groupby(iterable[,key_func=None])根据key_func(v)值分组的迭代器, 即如果对元素执行key_func运算,结果相同的元素会被划归一组,返回值是一个k,g元组for k, g in itertools.groupby(‘AAAABBBCCDAABBB’, key=lambda x: x==‘B’):print(k, list(g))→False [‘A’, ‘A’, ‘A’, ‘A’];True [‘B’, ‘B’, ‘B’];False [‘C’, ‘C’, ‘D’, ‘A’, ‘A’];True [‘B’, ‘B’, ‘B’]
islice(seq,[start,]stop[,step])对seq进行切片操作seq[start:stop:step]islice(‘ABCDEFG’, 2, None) → C,D,E,F,G
pairwise(iterable)将可迭代对象中的元素依顺序两两组队输出(p[0], p[1]), (p[1], p[2]),…pairwise(‘ABCDEFG’) → AB, BC, CD, DE, EF, FG
starmap(pred_func, seq)对seq中的元组执行pred_func操作func(*seq[0]), func(*seq[1]), …starmap(pow, [(2,5), (3,2), (10,3)])→ 32,9,1000
takewhile(pred_func, seq)输出元素直到seq中的元素在执行pred_func时返回Falseseq[0], seq[1], …, 直到pred_func真值测试失败takewhile(lambda x: x<5, [1,4,6,4,1]) → 1, 4
?tee(it, n)将一个迭代器拆分为n个迭代器。该迭代工具可能需要相当大的辅助存储空间(这取决于要保存多少临时数据)。通常,如果一个迭代器在另一个迭代器开始之前就要使用大部份或全部数据,使用 list() 会比 tee() 更快。it1, it2, … itn 将一个迭代器拆分为n个迭代器it = chain(‘ABC’, ‘DEF’) its = tee(it, 3) for it in its: print(list(it)) → [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’];[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’];[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]
zip_longset(p,q,…,fillvalue=None)将p,q,… 可迭代对象的元素组合为元组,长度不对齐时,可使用fillvalue补齐(p[0], q[0]), (p[1], q[1]), …zip_longest(‘ABCD’, ‘xy’, fillvalue=‘-’) → Ax,By,C-,D-

排列组合迭代器:

帮助我们快速实现数学中的排列、组合以及笛卡尔积运算。

迭代器描述运算规则示例
product(p,q[,repeat=1])生成可迭代对象的笛卡尔积((x,y) for x in for y in q) 相当于嵌套的for循环product(‘ABCD’, ‘xy’) → Ax Ay Bx By Cx Cy Dx Dy product(range(2), repeat=3) → 000 001 010 011 100 101 110 111
permutations(p[,r])从p中生成r个元素的所有可能的排列结果,无重复元素即数学意义上排列运算permutations(‘ABCD’, 2) → AB AC AD BA BC BD CA CB CD DA DB DC
combinations(p,r)从p中生成r个元素的搜有可能的组合结果,有序,无重复元素即数学意义上组合运算combinations(‘ABCD’, 2) → AB AC AD BC BD CD
combinations_with_replacement(p,r)从p中生成r个元素的搜有可能的组合结果,有序,元素可重复即数学意义上组合运算,允许每个元素重复出现combinations_with_replacement(‘ABCD’, 2) → AA AB AC AD BB BC BD CC CD DD

more-itertools库中的各类迭代器方法:

文档: https://more-itertools.readthedocs.io/en/stable/api.html

分类方法
Groupingchunked, ichunked, sliced, distribute, divide, split_at, split_before, split_after, split_into, split_when, bucket, unzip, grouper, partition
Lookahead and lookbackspy, peekable, seekable
Windowingwindowed, substrings, substrings_indexes, stagger, windowed_complete, pairwise, triplewise, sliding_window subslices,
Augmentingcount_cycle, intersperse, padded, mark_ends, repeat_last, adjacent, groupby_transform, pad_none, ncycles
Combiningcollapse, sort_together, interleave, interleave_longest, interleave_evenly, zip_offset, zip_equal, zip_broadcast, dotproduct, convolve, flatten, roundrobin, prepend, value_chain
Summarizingilen, unique_to_each, sample, consecutive_groups, run_length, map_reduce, exactly_n, is_sorted, all_equal, all_unique, minmax, first_true, quantify
Selectingislice_extended, first, last, one, only, strictly_n, strip, lstrip, rstrip, filter_except, map_except, nth_or_last, unique_in_window, before_and_after, nth, take, tail, unique_everseen, unique_justseen, duplicates_everseen, duplicates_justseen
Combinatoricsdistinct_permutations, distinct_combinations, circular_shifts, partitions, set_partitions, product_index, combination_index, permutation_index, powerset, random_product, random_permutation, random_combination, random_combination_with_replacement, nth_product, nth_permutation, nth_combination
Wrappingalways_iterable, always_reversible, countable, consumer, with_iter, iter_except
Otherslocate, rlocate, replace, numeric_range, side_effect, iterate, difference, make_decorator, SequenceView, time_limited, consume, tabulate, repeatfunc
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-07-04 22:49:56  更:2022-07-04 22:53:55 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/18 12:25:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码