[python]python中itertools详解

今天和朋友聊起了一个python的问题:两个迭代器如何合并成一个迭代器。我能想到的方法是将其转为list再进行相加,另一个朋友的方法是自己构造一个方法用yield返回一个生成器,再进行遍历,最后一个朋友告诉我们使用itertools的chain方法即可解决刚刚的那个问题,我也才想起来python的itertools库。
https://docs.python.org/2/library/itertools.html

itertools方法

1,chain: 将多个iterable合并为1个
chain(‘ABC’, ‘DEF’) --> A B C D E F
2,compress: 根据结果压缩
compress(‘ABCDEF’, [1,0,1,0,1,1]) --> A C E F
3,dropwhile: 筛选
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1

还有一些iter类型的
数组操作比如ifilter等

itertools其他方法

product: 笛卡尔集
比如product([1,2],[3,4],[5,6])会得到8个结果,分别是:[(1,3,5),(1,3,6),(1,4,5),(1,4,6),(2,3,5),(2,3,6),(2,4,5),(2,4,6)]
permutations:全排列
比如permutations([1,2,3], 3)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
combinations:有序排列
combinations([1,2,3,4], 3)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

你可能感兴趣的:(笔记,数据结构,2018-12)