iter
迭代器
<pre>
#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)
</pre>
Generators
生成器
<pre>
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))
</pre>
itertools模块
count(start=0, step=1)
count接收两个参数,start表示开始计数的基准数,step表示计数的幅度
<pre>
from itertools import count
for i in count(10,3): #从10开始每个3计数一次
if i > 20: #停止循环的条件
break
else:
print(i)
10
13
16
19
</pre>
islice(iterable, stop)表示从第一个iterable中去stop次
<pre>
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
</pre>
cycle(iterable)
接收一个可迭代的参数 例如[1,2,3]
表示可以无限循环这个3个数。1,2,3,1,2,3,........
<pre>
coding:UTF-8
from itertools import cycle
count = 0
for item in cycle('XYZ'):
if count > 7:
break
print(item)
count+=1
</pre>
repeat(object[, times])
重复第一个参数的对象 times次。如果没有指定times这表示无数次
<pre>
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]
</pre>
accumulate(iterable[, func])
返回一个累计的结构,func表示实现这个累计结构的方法。默认是累加
<pre>
from itertools import accumulate
def mul(x,y):
return xy
print(list(accumulate(range(1,5),lambda x,y:xy)))
也可以把lambda表达式换成mul
1,2,3,4
[1, 2, 6, 24]
</pre>
chain(*iterables)
组合几个可迭代对象的链。返回一个可迭代对象
<pre>
from itertools import chain
mylist = ['foo','bar']
num = list(range(6))
print(list(chain(mylist,num)))
['foo', 'bar', 0, 1, 2, 3, 4, 5]
</pre>
compress(data, selectors)
根据响应selectors来确定data里面内容,返回一个选择过后的itreable
<pre>
from itertools import compress
letters = 'ABCDEFG'
bools =[1,0,1,1,0]
print(list(compress(letters,bools)))
</pre>
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的作用相反。返回第一个不符合条件之前的内容
<pre>
from itertools import dropwhile
print(list(dropwhile(lambda x:x<5,[1,4,6,4,1])))
[6, 4, 1]
</pre>
filterfalse(predicate, iterable)
根据predicate 来过滤iterable里面的内容。返回不符合条件的内容
<pre>
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])))
</pre>
groupby(iterable, key=None)
the iterable needs to already be sorted on the same key function一般来说,进行分组的itreable,需要提前按照key(与传入groupby的key一样)进行排序
<pre>
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))
</pre>
starmap(function, iterable)
把iterable内容经过function处理后,返回一个新的迭代器
<pre>
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
</pre>
zip_longest(*iterables, fillvalue=None)
组合*iterables 的内容,如果不对等的话,用fillvalue顶替
<pre>
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')
</pre>
combinations(iterable, r)
(combinations_with_replacement与combinations功能类似,不过可以多了一个同一个元素之间的组合)
组合iterable里面的内容,r表示组合参数。如果r=2.表示两两组合
如果r>len(iterable)的话返回combinations,长度为0
<pre>
from itertools import combinations
print(list(combinations([1,2,3],2)))
</pre>
product(*iterables, repeat=1)
<pre>
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)]
</pre>
网友评论