python学习——itertools模块

count
count()会创建一个无限的迭代器
cycle
cycle()会把传入的一个序列无限重复下去
repeat
repeat()负责把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数
takewhile
通过takewhile()等函数根据条件判断来截取出一个有限的序列

itertools提供的几个迭代器操作函数更加有用:
chain
chain()可以把一组迭代对象串联起来,形成一个更大的迭代器
groupby
groupby()把迭代器中相邻的重复元素挑出来放在一起:

from operator import itemgetter
from itertools import groupby

rows = [
    {'address':'5412 N CLARK', 'date': '07/01/2012'},
    {'address':'5148 N CLARK', 'date': '07/04/2012'},
    {'address':'5800 E 58TH', 'date': '07/02/2012'},
    {'address':'2122 N CLARK', 'date': '07/03/2012'},
    {'address':'5645 N RAVENSWOOD', 'date': '07/02/2012'},
    {'address':'1060 W ADDISON', 'date': '07/02/2012'},
    {'address':'4801 N BROADWAY', 'date': '07/01/2012'},
    {'address':'1039 W GRANVILLE', 'date': '07/04/2012'},
]

rows.sort(key=itemgetter('date'))
for date, items in groupby(rows, key=itemgetter('date')):
    print(date)
    for item in items:
        print('   ',item)

#输出结果:
07/01/2012
    {'date': '07/01/2012', 'address': '5412 N CLARK'}
    {'date': '07/01/2012', 'address': '4801 N BROADWAY'}
07/02/2012
    {'date': '07/02/2012', 'address': '5800 E 58TH'}
    {'date': '07/02/2012', 'address': '5645 N RAVENSWOOD'}
    {'date': '07/02/2012', 'address': '1060 W ADDISON'}
07/03/2012
    {'date': '07/03/2012', 'address': '2122 N CLARK'}
07/04/2012
    {'date': '07/04/2012', 'address': '5148 N CLARK'}
    {'date': '07/04/2012', 'address': '1039 W GRANVILLE'}

imap
imap()和map()的区别在于,imap()可以作用于无穷序列,并且,如果两个序列的长度不一致,以短的那个为准。

for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
     print x

#输出结果:
10
40
90

注意imap()返回一个迭代对象,而map()返回list。当你调用map()时,已经计算完毕:

>>> r = map(lambda x: x*x, [1, 2, 3])
>>> r # r已经计算出来了
[1, 4, 9]

当你调用imap()时,并没有进行任何计算:

>>> r = itertools.imap(lambda x: x*x, [1, 2, 3])
>>> r
<itertools.imap object at 0x103d3ff90>
# r只是一个迭代对象

必须用for循环对r进行迭代,才会在每次循环过程中计算出下一个元素:

>>> for x in r:
...     print x
...
1
4
9

ifilter
ifilter()就是filter()的惰性实现
compress
notable filtering tool is itertools.compress() , which takes an iterable and an
accompanying Boolean selector sequence as input. As output, it gives you all of the items in the
iterable where the corresponding element in the selector is True .

addresses = [
    'CLARK',
    'CLARK',
    '58TH',
    'CLARK'
    'RAVENSWOOD',
    'ADDISON',
    'BROADWAY',
    'GRANVILLE',
]
counts = [ 0, 3, 10, 4, 1, 7, 6, 1]
>>> from itertools import compress
>>> more5 = [n > 5 for n in counts]
>>> more5
[False, False, True, False, False, True, True, False]
>>> list(compress(addresses, more5))
['5800 E 58TH', '4801 N BROADWAY', '1039 W GRANVILLE']
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值