python itertools 模块完全掌握(1)

1. 全部

  1. count(start=0, step=1)
  2. repeat(elem [,n])
  3. accumulate(p[, func])
  4. chain(p, q, …)
  5. chain.from_iterable([p, q, …])
  6. compress(data, selectors)
  7. dropwhile(pred, seq)
  8. groupby(iterable[, keyfunc])
  9. filterfalse(pred, seq)
  10. islice(seq, [start,] stop [, step])
  11. starmap(fun, seq)
  12. tee(it, n=2)
  13. takewhile(pred, seq)
  14. zip_longest(p, q, …)
  15. product(p, q, … [repeat=1])
  16. permutations(p[, r])
  17. combinations(p, r)
  18. combinations_with_replacement(p, r)
    本节主要介绍1-7,8-18见下一节内容

2. 详解

#!/usr/bin/env python
# encoding: utf-8


"""
@python version: ??
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@site: http://blog.csdn.net/github_36326955
@software: PyCharm
@file: suggest4.py
@time: 5/2/2017 5:04 PM
"""
import itertools

# ex1:无限迭代器
# ex1.1: count(start, step)
for x in itertools.count(start=0, step=1):
    print(x, end=',')

# ex1.2: cycle(iter)
for x in itertools.cycle('abcd '):
    print(x, end='')

# ex1.3: repeat(iter, times)
for x in itertools.repeat('abc',times=10):
    print(x, end=',')

# ex2:终止于最短输入序列的迭代器
# ex2.1: accumulate
for x in itertools.accumulate("abc"):
    print(x, end="|")

# 上面的代码默认参数func相当于下面的代码:
def binary_fun(x, y):
    return x+y
for x in itertools.accumulate("abc",func=binary_fun):
    print(x, end="|")

# 进一步地,你也可以自定义其他二值函数,例如:
def reverse(x, y):
    return y+x
for x in itertools.accumulate("abc",func=reverse):      # 输出每一步倒序的结果
    print(x, end="|")

# ex2.2:chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ...
for x in itertools.chain("abc", "def", "ghi"):
    print(x, end='')

# 另外的一种用法:
#chain.from_iterable([p, q, ...]) --> p0, p1, ... plast, q0, q1, ...
for x in itertools.chain.from_iterable(["abc", [1, 2, 3], ('have', 'has')]):
    print(x, end="|")

# ex2.3:compress
# compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...
for x in itertools.compress(['a', 'b', 'c'], [1, 0, 1]):
    print(x, end=',')
"""
output:
a,c,
"""

# ex2.4:dropwhile
# dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails
# 创建一个迭代器,for item in seq,只要函数pred(item)为True,
# 就丢弃seq中的项item,如果pred(item)返回False,就会生成seq中的项和所有后续项。
def pred(x):
    print('Testing:', x)
    return x < 1

for x in itertools.dropwhile(pred, [-1, 0, 1, 2, 3, 4, 1, -2]):
    print('Yielding:', x)
"""
output:
Testing: -1
Testing: 0
Testing: 1
Yielding: 1
Yielding: 2
Yielding: 3
Yielding: 4
Yielding: 1
Yielding: -2
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值