itertools详解

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

itertools详解
Python中有⼀种特有的概念,称之为迭代器。

迭代器最⼤的特点是惰性求值,即只有当迭代⾄某个值时,才会对其进⾏计算,⽽不是⼀开始就计算出全部的值。

迭代器特别适合应⽤于⼤⽂件,⽆限集合等,因为⽆需将他们⼀次性传⼊内存中。

itertools是Python内置的模块,其中包含了⼀系列迭代器相关的函数和类。

本⽂将主要学习⼀下这些⽅法的使⽤。

count
count() 接收两个参数,第⼀个参数指定开始值,默认为 0,第⼆个参数指定步长,默认为 1。

作⽤是创建⼀个从 firstval (默认值为 0) 开始,以 step (默认值为 1) 为步长的的⽆限整数迭代器。

import itertools
nums = itertools.count(1, 2)
for i in nums:
if i > 10:
break
print i
# 1
# 3
# 5
# 7
# 9
cycle
cycle(iterable)接收⼀个迭代器作为参数。

作⽤是对 iterable 中的元素反复执⾏循环,返回迭代器。

import itertools
nums = itertools.cycle("nian")
index = 0
for i in nums:
index += 1
if index > 10:
break
print i
# n
# i
# a
# n
# n
# i
# a
# n
# n
# i
repeat
repeat(object, times)接收两个参数,第⼀个参数是被重复的对象,第⼆个参数为重复的次数。

作⽤是重复⽣成多个对象。

import itertools
for element in itertools.repeat([1,2,3], 3):
print element
# [1, 2, 3]
# [1, 2, 3]
# [1, 2, 3]
chain
chain的使⽤格式如下:chain(iterable1, iterable2, iterable3, ...)
作⽤是接收多个迭代器,并将他们连接起来返回⼀个新的迭代器。

from itertools import chain
for item in chain([1,2,3], [4,5,6]):
print item
# 1
# 2
# 3
# 4
# 5
# 6
chain还有另外⼀个⽤法:即接收⼀个可迭代对象作为参数,并输出⼀个迭代器。

from itertools import chain
string = chain.from_iterable('ABCD')
print string.next()
# A
compress
compress的使⽤格式如下:compress(data, selectors)
作⽤如下:⽤于对数据进⾏筛选,当 selectors 的某个元素为 true 时,则保留 data 对应位置的元素,否则去除。

from itertools import compress
print list(compress('ABCDEF', [1, 1, 0, 1, 0, 1]))
# ['A', 'B', 'D', 'F']
print list(compress('ABCDEF', [1, 1, 0, 1]))
# ['A', 'B', 'D']
print list(compress('ABCDEF', [True, False, True]))
# ['A', 'C']
dropwhile
dropwhile的使⽤形式如下:dropwhile(function, iterable)
其中,第⼀个参数是⼀个函数,第⼆个参数是⼀个可迭代对象。

作⽤如下:对于 iterable 中的元素,如果 function(item) 为 true,则丢弃该元素,否则返回该项及所有后续项。

from itertools import dropwhile
print list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
# [6, 2, 1]
print list(dropwhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
# [2, 1, 6, 5, 4]
groupby
groupby的使⽤形式如下:groupby(iterable[, keyfunc])
作⽤如下:iterable 是⼀个可迭代对象,keyfunc 是分组函数,⽤于对 iterable 的连续项进⾏分组。

如果不指定keyfunc,则默认对 iterable 中的连续相同值进⾏分组,返回⼀个 (key, sub-iterator) 的迭代器。

from itertools import groupby
for key, value_iter in groupby('aaabbbaaccd'):
print key, ':', list(value_iter)
# a : ['a', 'a', 'a']
# b : ['b', 'b', 'b']
# a : ['a', 'a']
# c : ['c', 'c']
# d : ['d']
data = ['a', 'bb', 'cc', 'ddd', 'eee', 'f']
for key, value_iter in groupby(data, len):
print key, ':', list(value_iter)
# 1 : ['a']
# 2 : ['bb', 'cc']
# 3 : ['ddd', 'eee']
# 1 : ['f']
data = ['a', 'bb', 'ccc', 'dd', 'eee', 'f']
for key, value_iter in groupby(data, len):
print key, ':', list(value_iter)
# 1 : ['a']
# 2 : ['bb']
# 3 : ['ccc']
# 2 : ['dd']
# 3 : ['eee']
# 1 : ['f']
# Ps:函数处理后得到的值连续时会分为同⼀个组。

ifilter/ifilterfalse
形式如下:ifilter(function or None, iterable)
作⽤:将 iterable 中 function(item) 为 True 的元素组成⼀个迭代器返回,如果 function 是 None,则返回 iterable 中所有计算为 True 的项。

from itertools import ifilter
print list(ifilter(lambda x: x < 6, range(10)))
# [0, 1, 2, 3, 4, 5]
print list(ifilter(None, [0, 1, 2, 0, 3, 4]))
# [1, 2, 3, 4]
ifilterfalse与ifilter类似,将 iterable 中 function(item) 为 False 的元素组成⼀个迭代器返回。

from itertools import ifilterfalse
print list(ifilterfalse(lambda x: x < 6, range(10)))
print list(ifilter(None, [0, 1, 2, 0, 3, 4]))
# [0, 0]
islice
形式如下:islice(iterable, [start,] stop [, step])
其中,iterable 是可迭代对象,start 是开始索引,stop 是结束索引,step 是步长,start (默认为0)和 step(默认为1)可选。

作⽤是将⼀个可迭代对象进⾏切割,返回⼀个新的迭代器。

from itertools import count, islice
print list(islice([10, 6, 2, 8, 1, 3, 9], 5))
# [10, 6, 2, 8, 1]
print list(islice(count(), 6))
# [0, 1, 2, 3, 4, 5]
print list(islice(count(), 3, 10))
# [3, 4, 5, 6, 7, 8, 9]
print list(islice(count(), 3, 10 ,2))
# [3, 5, 7, 9]
imap
形式如下:imap(func, iter1, iter2, iter3, ...)
作⽤是:imap 返回⼀个迭代器,元素为 func(i1, i2, i3, ...),i1,i2 等分别来源于 iter, iter2。

from itertools import imap
print imap(str, [1, 2, 3, 4])
# <itertools.imap object at 0x10556d050>
print list(imap(str, [1, 2, 3, 4]))
# ['1', '2', '3', '4']
print list(imap(pow, [2, 3, 10], [4, 2, 3]))
# [16, 9, 1000]
tee
形式如下:tee(iterable [,n])
作⽤是:⽤于从 iterable 创建 n 个独⽴的迭代器,以元组的形式返回,n 的默认值是 2。

from itertools import tee
print tee('abcd') # n 默认为 2,创建两个独⽴的迭代器
# (<itertools.tee object at 0x1049957e8>, <itertools.tee object at 0x104995878>)
iter1, iter2 = tee('abcde')
print list(iter1)
# ['a', 'b', 'c', 'd', 'e']
print list(iter2)
# ['a', 'b', 'c', 'd', 'e']
print tee('abc', 3) # 创建三个独⽴的迭代器
# (<itertools.tee object at 0x104995998>, <itertools.tee object at 0x1049959e0>, <itertools.tee object at 0x104995a28>) takewhile
形式如下:takewhile(function, iterable)
其中,function是函数,iterable 是可迭代对象。

作⽤是:对于 iterable 中的元素,如果 function(item) 为 true,则保留该元素,只要 function(item) 为 false,则⽴即停⽌迭代。

from itertools import takewhile
print list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
# [1, 3]
print list(takewhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
# []
izip
形式如下:izip(iter1, iter2, ..., iterN)
作⽤是:⽤于将多个可迭代对象对应位置的元素作为⼀个元组,将所有元组『组成』⼀个迭代器,并返回。

Ps:如果某个可迭代对象不再⽣成值,则迭代停⽌。

from itertools import izip
for item in izip('ABCD', 'xy'):
print item
# ('A', 'x')
# ('B', 'y')
for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
print item
# (1, 'a')
# (3, 'c')
izip_longest
形式如下: izip_longest(iter1, iter2, ..., iterN, [fillvalue=None])
作⽤是:跟 izip 类似,但迭代过程会持续到所有可迭代对象的元素都被迭代完。

如果有指定 fillvalue,则会⽤其填充缺失的值,否则为 None。

from itertools import izip_longest
for item in izip_longest('ABCD', 'xy'):
print item
# ('A', 'x')
# ('B', 'y')
# ('C', None)
# ('D', None)
for item in izip_longest('ABCD', 'xy', fillvalue='-'):
print item
# ('A', 'x')
# ('B', 'y')
# ('C', '-')
# ('D', '-')
product
形式如下:product(iter1, iter2, ... iterN, [repeat=1])
其中,repeat 是⼀个关键字参数,⽤于指定重复⽣成序列的次数。

作⽤是:⽤于求多个可迭代对象的笛卡尔积,它跟嵌套的for循环等价。

from itertools import product
for item in product('ABCD', 'xy'):
print item
# ('A', 'x')
# ('A', 'y')
# ('B', 'x')
# ('B', 'y')
# ('C', 'x')
# ('C', 'y')
# ('D', 'x')
# ('D', 'y')
print list(product('ab', range(3)))
# [('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2)]
print list(product((0,1), (0,1), (0,1)))
# [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
print list(product('ABC', repeat=2))
# [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')] permutations
形式如下:permutations(iterable[, r])
作⽤是:⽤于⽣成⼀个排列、
其中,r 指定⽣成排列的元素的长度,如果不指定,则默认为可迭代对象的元素长度。

from itertools import permutations
print permutations('ABC', 2)
# <itertools.permutations object at 0x1074d9c50>
print list(permutations('ABC', 2))
# [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
print list(permutations('ABC'))
# [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')] combinations
形式如下:combinations(iterable, r)
作⽤是:⽤于求序列的组合,其中,r 指定⽣成组合的元素的长度。

from itertools import combinations
print list(combinations('ABC', 2))
# [('A', 'B'), ('A', 'C'), ('B', 'C')]
combinations_with_replacement
形式如下:combinations_with_replacement(iterable, r)
作⽤是:和 combinations 类似,但它⽣成的组合包含⾃⾝元素。

from itertools import combinations_with_replacement
# [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]。

相关文档
最新文档