您的位置:首页 > 编程语言 > Python开发

python itertools 模块完全掌握(1)

2017-05-02 17:54 579 查看

1. 全部

count(start=0, step=1)

repeat(elem [,n])

accumulate(p[, func])

chain(p, q, …)

chain.from_iterable([p, q, …])

compress(data, selectors)

dropwhile(pred, seq)

groupby(iterable[, keyfunc])

filterfalse(pred, seq)

islice(seq, [start,] stop [, step])

starmap(fun, seq)

tee(it, n=2)

takewhile(pred, seq)

zip_longest(p, q, …)

product(p, q, … [repeat=1])

permutations(p[, r])

combinations(p, r)

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
, 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
"""
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: