迭代器和生成器

iter

迭代器

#coding:UTF-8
class MyIterator:
    def __init__(self,letters):
        """
        Constructor
        """
        self.letters = letters
        self.position = 0

    def __iter__(self):  #重写这个方法表示支持迭代
        """
        Returns itself as an iterator
        """
        return self

    def __next__(self):  #返回容器的下一个元素。没有就报错

        if self.position >= len(self.letters):
            raise StopIteration
        letter = self.letters[self.position]
        self.position += 1
        return letter

if __name__ == '__main__':
    i = MyIterator('abcde')
    for item in i:
        print(item)

Generators

生成器

#coding:UTF-8
def double_generator():
    num = 2
    while num<16*16:
        yield num
        num *= num
def silly_gen():
    yield "Python"
    yield "Rocks"
    yield "So do you"
if __name__ == '__main__':
    # gen = silly_gen()
    # for item in gen:
    #   print(item)
    gen = double_generator()
    print(next(gen))
    print(next(gen))
    print(next(gen))

itertools模块

count(start=0, step=1)
count接收两个参数,start表示开始计数的基准数,step表示计数的幅度

>>>from itertools import count
>>> for i in count(10,3):  #从10开始每个3计数一次
        if i > 20:    #停止循环的条件
            break
        else:
            print(i)
>>>
10
13
16
19

islice(iterable, stop)表示从第一个iterable中去stop次

from itertools import count
from itertools import islice
if __name__ == '__main__':
    for i in islice(count(10),5):
        print(i)
>>>10,11,12,13,14

cycle(iterable)

接收一个可迭代的参数 例如[1,2,3]
表示可以无限循环这个3个数。1,2,3,1,2,3,........

#coding:UTF-8
from itertools import cycle
count = 0
for item in cycle('XYZ'):
    if count > 7:
        break
    print(item)
    count+=1

repeat(object[, times])

重复第一个参数的对象 times次。如果没有指定times这表示无数次

from itertools import repeat
for i in repeat([1,2,3,4,5],5):
    print(i)
>>>
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

accumulate(iterable[, func])

返回一个累计的结构,func表示实现这个累计结构的方法。默认是累加

from itertools import accumulate
def mul(x,y):
    return x*y
print(list(accumulate(range(1,5),lambda x,y:x*y)))
>>>
也可以把lambda表达式换成mul
#1,2,3,4
[1, 2, 6, 24]

chain(*iterables)

组合几个可迭代对象的链。返回一个可迭代对象

from itertools import chain
mylist = ['foo','bar']
num = list(range(6))
print(list(chain(mylist,num)))
>>>
['foo', 'bar', 0, 1, 2, 3, 4, 5]

compress(data, selectors)

根据响应selectors来确定data里面内容,返回一个选择过后的itreable

from itertools import compress
letters = 'ABCDEFG'
bools =[1,0,1,1,0]
print(list(compress(letters,bools)))

dropwhile(predicate, iterable) takewhile(predicate, iterable)

Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element
根据predicate 来过滤iterable里面的内容。返回第一个不符合条件之后的内容

takewhile(predicate, iterable) 与dropwhile的作用相反。返回第一个不符合条件之前的内容

from itertools import dropwhile
print(list(dropwhile(lambda x:x<5,[1,4,6,4,1])))
>>> [6, 4, 1]

filterfalse(predicate, iterable)

根据predicate 来过滤iterable里面的内容。返回不符合条件的内容

from itertools import filterfalse
def greater_than_five(x):
    return x > 5
print(list(filterfalse(greater_than_five,[6,7,8,9,10,1,2,3,4])))

groupby(iterable, key=None)

the iterable needs to already be sorted on the same key function一般来说,进行分组的itreable,需要提前按照key(与传入groupby的key一样)进行排序

from itertools import groupby
vehicles = [('Ford', 'Taurus'), ('Dodge', 'Durango'),
('Chevrolet', 'Cobalt'), ('Ford', 'F150'),
('Dodge', 'Charger'), ('Ford', 'GT')]
#排序 按照元祖的第一个元素排序
sorted_vehicles = sorted(vehicles,key=lambda x:x[0])
# print(sorted_vehicles)
for key,group in groupby(sorted_vehicles,lambda make:make[0]):
    print('-->',key,'-->')
    for make,model in group:
        print('{model} is made by {make}'.format(model=model,make=make))

starmap(function, iterable)

把iterable内容经过function处理后,返回一个新的迭代器

from itertools import starmap
def add(a,b):
    return a+b
def contact(x):
    return 'AF'+x
for item in starmap(add,[(2,3),(4,5)]):
    print(item)
for item in starmap(contact,['e','d','f','g']):
    print(item)
>>>
5
9
AFe
AFd
AFf
AFg

zip_longest(*iterables, fillvalue=None)

组合*iterables 的内容,如果不对等的话,用fillvalue顶替

from itertools import zip_longest
for item in zip_longest('ABCD','zyx','12',fillvalue = 'BANK'):
    print(item)
>>>
('A', 'z', '1')
('B', 'y', '2')
('C', 'x', 'BANK')
('D', 'BANK', 'BANK')

combinations(iterable, r)

(combinations_with_replacement与combinations功能类似,不过可以多了一个同一个元素之间的组合)
组合iterable里面的内容,r表示组合参数。如果r=2.表示两两组合
如果r>len(iterable)的话返回combinations,长度为0

from itertools import combinations
print(list(combinations([1,2,3],2)))

product(*iterables, repeat=1)

from itertools import product
print(list(product((1,-1),(3,-3),(5,-5,4))))
>>>
[(1, 3, 5), (1, 3, -5), (1, 3, 4), (1, -3, 5),
 (1, -3, -5), (1, -3, 4), (-1, 3, 5), (-1, 3, -5), 
(-1, 3, 4), (-1, -3, 5), (-1, -3, -5), (-1, -3, 4)]

你可能感兴趣的:(迭代器和生成器)