Python--进阶处理4

#================第四章:迭代器和生成器===================

# 函数 itertools.islice()适用于在迭代器和生成器上做切片操作。

import itertools


def count(n):
while n < 30:
yield n
n += 1

c = count(0)
for x in itertools.islice(c, 10, 20):
print(x)

# itertools.dropwhile() 函数
# 给它传递一个函数对象和一个可迭代对 象。
# 它会返回一个迭代器对象,丢弃原有序列中直到函数返回 True 之前的所有元素, 然后返回后面所有元素。

# 遍历一个集合中元素的所有可能的排列或组合
# itertools.permutations() ,它接受一个集合并产生一个元组序列
# 得到指定长度的所有排列,可以传递一个可选的长度参数
from itertools import permutations

items = ['a', 'b', 'c']
for item in permutations(items, 2):
print(item)

# 使用 itertools.combinations() 可得到输入集合中元素的所有的组合
from itertools import combinations

for c in combinations(items, 3):
print(c)

# 函数 itertools.combinations with replacement() 允许同一个元素被选择多次
from itertools import combinations_with_replacement
for c in combinations_with_replacement(items, 3):
print(c)

# 在迭代一个序列的同时跟踪正在被处理的元素索引
# 内置的 enumerate() 函数可以很好的解决这个问题
my_list = ['a', 'b', 'c']
for idx, val in enumerate(my_list, 1):
print(idx, val)
data = [(1, 2), (3, 4), (5, 6), (7, 8)]
for n, (x, y) in enumerate(data, 1):
print(n, (x, y))

# 同时迭代多个序列,每次分别从一个序列中取一个元素
# 为了同时迭代多个序列,使用 zip() 函数
# 迭代长度跟参数中最短序列长度一致
xpts = ['a', 'b', 'c', 'd']
ypts = [101, 78, 37, 15, 99, 36]
for x, y in zip(xpts, ypts):
print(x, y)
# itertools.zip longest() 函数
from itertools import zip_longest
for i in zip_longest(xpts, ypts, fillvalue='nb'):
print(i)

# 在多个对象执行相同的操作
# 使用itertools.chain() 方法
# 接受一个或多个可迭代对象列表作为 输入,并返回一个迭代器
from itertools import chain
zpts = ('one', 'two', 'three')
for xy in chain(xpts, ypts, zpts):
print(xy)

# 创建数据处理管道
# 生成器函数是一个实现管道机制的好办法

# 展开嵌套的序列
# 可以写一个包含 yield from 语句的递归生成器
from collections import Iterable

def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x


items = [1, 2, [3, 4, [5, 6], 7], 8]
for x in flatten(items):
print(x)

# 一系列排序序列,想将它们合并后得到一个排序序列并在上面迭代遍历
# heapq.merge() 函数可以解决这个问题
import heapq

a = [1, 4, 7, 10]
b = [3, 5, 6, 11]
c = list(heapq.merge(a, b))
print(c)



原文地址:https://www.cnblogs.com/fqfanqi/p/8433439.html