Python: itertools模块任性迭代
admin
2023-07-30 21:34:55
0

itertools 模块

该模块包含了一系列处理可迭代对象(sequence-like)的函数,从此迭代更任性。

迭代器有一些特点,比如lazy,也就是只有用到的时候才读入到内存里,这样更快更省内存;比如只能调用一次,会被消耗掉。

import itertools as itls

合并迭代器: chain()与izip()

chain()函数接收n个可迭代对象,然后返回一个他们的合集的迭代器,纵向合并,上例子。

for i in itls.chain([1,2,3],[\'a\',\'b\',\'c\']):
    print i,
1 2 3 a b c

izip()函数接收n个可迭代对象,然后将其合并成tuples,横向合并,功能类似zip(),只是返回的是iterator,而不是list。

for i, j in itls.izip([1,2,3],[\'a\',\'b\',\'c\']):
    print i, j
1 a
2 b
3 c

切分迭代器: islice()

islice()函数接收一个迭代器,然后返回其切片,类似于listslice切片操作。参数有startstopstep,其中startstep参数时可选参数。

print \"Stop at 5:\"
for i in itls.islice(itls.count(),5):
    print i,
Stop at 5:
0 1 2 3 4
print \"Start at 5, Stop at 10:\"
for i in itls.islice(itls.count(),5,10):
    print i,
Start at 5, Stop at 10:
5 6 7 8 9
print \"By tens to 100:\"
for i in itls.islice(itls.count(),0,100,10):
    print i,
By tens to 100:
0 10 20 30 40 50 60 70 80 90

复制迭代器: tee()

与Unix里tee方法语意一样,这里接收一个迭代器,然后返回n个(default 2)一样的迭代器。

r = itls.islice(itls.count(),4)
i1, i2, i3 = itls.tee(r,3) # i1 and i2, like a copy

for i, j, k in itls.izip(i1,i2,i3):
    print i, j, k
0 0 0
1 1 1
2 2 2
3 3 3

有一点值得注意,初始的iterator不宜继续使用,如果你使用(consume),那新的迭代器就不会产生这些值了,见例子。

r = itls.islice(itls.count(),4)
i1, i2 = itls.tee(r)
for i in r:
    print \'r:\', i
    if i > 0:
        break
for i in i1:
    print \'i1:\', i

for i in i2:
    print \'i2:\', i
r: 0
r: 1
i1: 2
i1: 3
i2: 2
i2: 3

可以看出,初始迭代器消耗了0,1,在新产生的迭代器里,就不会出现这些值了。

Map迭代器

imap()函数对迭代器进行转换,类似于python内置的map()函数。下例把xrange(5)乘以2。

print \"Doubles:\"
for i in itls.imap(lambda x: 2*x, xrange(5)):
    print i,
Doubles:
0 2 4 6 8

imap()可以同时接受多个可迭代对象,进行map操作。

print \"Multiples:\"
for i in itls.imap(lambda x,y:(x, y, x*y), xrange(5),xrange(5,10)):
    print \'%d * %d = %d\' % i
Multiples:
0 * 5 = 0
1 * 6 = 6
2 * 7 = 14
3 * 8 = 24
4 * 9 = 36

starmap()imap()功能类似,但有点区别,starmap()可以从tuple里解析出多个参数,而imap()只能从多个课迭代对象获取多个参数,看例子。

values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
for i in itls.starmap(lambda x,y:(x,y,x*y), values):
    print \'%d * %d = %d\' % i
0 * 5 = 0
1 * 6 = 6
2 * 7 = 14
3 * 8 = 24
4 * 9 = 36

产生新迭代器

count()cycle()repeat()函数提供了几个产生迭代器的便捷操作,非常nice。

count()

产生连续的整数,有下限(默认0),没有上限(可以用xrange())。

for i in itls.izip(itls.count(1),[\'a\',\'b\',\'c\']):
    print i
(1, \'a\')
(2, \'b\')
(3, \'c\')

cycle()

无限重复给定的可迭代对象。

i = 0
for item in itls.cycle([\'a\',\'b\',\'c\']):
    i += 1
    if i == 7:
        break
    print (i, item)
(1, \'a\')
(2, \'b\')
(3, \'c\')
(4, \'a\')
(5, \'b\')
(6, \'c\')

repeat()

重复给定的值,n次。

for i in itls.repeat(\'over-and-over\',3):
    print i
over-and-over
over-and-over
over-and-over

当需要给一个序列添加一个不变对象的时候,用repeat()imap()izip()的combo特别有用。

for i,s in itls.izip(itls.count(), itls.repeat(\'over-and-over\',3)):
    print i, s
0 over-and-over
1 over-and-over
2 over-and-over
for i in itls.imap(lambda x,y:(x,y,x*y),itls.repeat(2),xrange(5)):
    print \'%d * %d = %d\' % i
2 * 0 = 0
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8

过滤迭代器

类似于内置的filter()功能,实现迭代器的筛选。

dropwhile()

对item进行判断,如果判断为True,继续;如果判断为False,不继续drop了,只drop之前判断为True的,保留之后的所有items,不再进行判断,全部保留。

def should_drop(x):
    print \'Testing:\', x
    return x < 1
for i in itls.dropwhile(should_drop,[ -1, 0, 1, 2, 3, 1, -2 ]):
    print \'Yielding:\', i
Testing: -1
Testing: 0
Testing: 1
Yielding: 1
Yielding: 2
Yielding: 3
Yielding: 1
Yielding: -2

takewhile()

dropwhile()功能相反,当判断为False的时候,就不继续take了,只保留之前判断为真item。

def should_take(x):
    print \'Testing:\', x
    return x < 2
for i in itls.takewhile(should_take,[ -1, 0, 1, 2, 3, 4, 1, -2 ]):
    print \'Yielding:\', i
Testing: -1
Yielding: -1
Testing: 0
Yielding: 0
Testing: 1
Yielding: 1
Testing: 2

ifilter()

dropwhile()takewhile()都不是对所有元素过滤,而ifilter()则尽职尽责地对所有元素过滤。与其对应的是ifilterfalse(),只保留判定为False的item。

def check_item(x):
    print \'Testing:\', x
    return x < 1
for i in itls.ifilter(check_item, [ -1, 0, 1, 2, 3, -2 ]):
    print \'Yielding:\', i
Testing: -1
Yielding: -1
Testing: 0
Yielding: 0
Testing: 1
Testing: 2
Testing: 3
Testing: -2
Yielding: -2

Group迭代器

groupby(iterable[, keyfunc]) Create an iterator which returns(key, sub-iterator) grouped by each value of key(value)

按给定的key对可迭代对象分组,返回sub-iterator

things = [(\"animal\", \"bear\"), (\"animal\", \"duck\"), (\"plant\", \"cactus\"), (\"vehicle\", \"speed boat\"), (\"vehicle\", \"school bus\")]

groupby()接收两个参数,一个the data to group,一个是the function to group it with

for key, group in itls.groupby(things, lambda x: x[0]):
    print key, group
animal 
plant 
vehicle 

可以看出,分组后,返回三个sub-iterator,我们可以再用一层循环访问。

for key, group in itls.groupby(things, lambda x:x[0]):
    for thing in group:
        print \"A %s is a %s.\" % (thing[1], key)
    print \"\"
A bear is a animal.
A duck is a animal.

A cactus is a plant.

A speed boat is a vehicle.
A school bus is a vehicle.

且慢,值得注意的一点是,在group之前,务必要按key排序,因为groupby方法遍历对象,当key变化的时候,就会新产生一个group。有例为证!

things = [(\"animal\", \"bear\"), (\"plant\", \"cactus\"), (\"animal\", \"duck\")]
for key, group in itls.groupby(things, lambda x: x[0]):
    print key, group
animal 
plant 
animal 

本来是应该分两组的,结果是三组,就是因为没有排序。

new_things = sorted(things,key=lambda x: x[0])
for key, group in itls.groupby(new_things, lambda x:x[0]):
    print key, group
animal 
plant 

这个看上去就对了!

相关内容

热门资讯

Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...
python清除字符串里非数字... 本文实例讲述了python清除字符串里非数字字符的方法。分享给大家供大家参考。具体如下: impor...