python itertools 模块完全掌握(1)

来源:互联网 发布:怎么添加usb端口 编辑:程序博客网 时间:2024/05/17 23:38

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: accumulatefor x in itertools.accumulate("abc"):    print(x, end="|")# 上面的代码默认参数func相当于下面的代码:def binary_fun(x, y):    return x+yfor x in itertools.accumulate("abc",func=binary_fun):    print(x, end="|")# 进一步地,你也可以自定义其他二值函数,例如:def reverse(x, y):    return y+xfor 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 < 1for x in itertools.dropwhile(pred, [-1, 0, 1, 2, 3, 4, 1, -2]):    print('Yielding:', x)"""output:Testing: -1Testing: 0Testing: 1Yielding: 1Yielding: 2Yielding: 3Yielding: 4Yielding: 1Yielding: -2"""
0 0
原创粉丝点击