Python 迭代器模組 itertools
阿新 • • 發佈:2018-12-06
from itertools import chain test = chain('AB', 'CDE', 'F') for el in test: print(el)
"""
A
B
C
D
E
F
"""
from itertools import chain
for i in chain([1,2,3], ['a', 'b', 'c']):
print (i)
"""
1
2
3
a
b
c
"""
from itertools import starmap
values = [[0,5], [1,6], [2,7], [3,8]]
for i in starmap(lambda x, y:(x, y, x+y), values):
print ('%d * %d = %d' % i)
"""
0 * 5 = 5
1 * 6 = 7
2 * 7 = 9
3 * 8 = 11
"""
from itertools import combinations
test = combinations([1, 2, 3, 4], 2)
for el in test:
print(el)
"""
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
"""
from itertools import compress
letters = 'ABCDEFG'
bools = [True, False, True, True,False]
ret = list(compress(letters, bools))
print(ret)
"""
['A', 'C', 'D']
"""
from itertools import filterfalse
def greater_than_five(x):
return x > 5
ret = list(filterfalse(greater_than_five, [0,6, 7, 8, 9, 1, 2, 3, 10,2]))
print(ret)
"""
[0, 1, 2, 3, 2]
"""
from itertools import islice
iterator = islice('123456', 4)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
"""
1
2
3
4
"""
from itertools import cycle
polys = ['13579', '02468', '56789', '01234']
iterator = cycle(polys)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
"""
13579
02468
56789
01234
13579
02468
"""
#repeat(物件[, 次數])
from itertools import repeat
iterator = repeat("123", 5)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
from itertools import starmap
def add(a, b):
return a+b
for item in starmap(add, [[2,3], (4,5),(7,8)]):
print(item)
"""
5
9
15
"""