python itertools usage

1. Introduction
Itertools is an iterator module of python. The tools provided by itertools are quite efficient and save memory.
Using these tools, you will be able to create your own custom iterators for efficient loops.

  • Infinite Iterator The
     itertools package comes with three iterators that can iterate infinitely. This means that when you use them, you need to know whether you want an iterator that will eventually stop, or you need to iterate shoes indefinitely.

(1) count (initial value = 0, step size = 1): the count iterator will return evenly spaced values ​​starting from the incoming start parameter. count can also receive a specified step parameter. Let's look at a simple example:

from itertools import count
for i in count():
    print i
    if i > 10:
        break

#从0开始循环
0
1
2
3
4
5
6
7
8
9
10
11

(2) islice(count(10), 5): Start from 10 and end after outputting 5 elements. The second parameter of islice controls when to stop the iteration. But its meaning is not "stop when the number 5 is reached", but "stop after 5 iterations".

from itertools import count,islice
for i in islice(count(10),5):
    print i

#从10开始循环迭代5次后退出循环
10
11
12
13
14

(3) Cycle: Here we create a for loop to loop infinitely between the three letters XYZ. Of course, we don't really want to loop forever, so we added a simple counter to break out of the loop.

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

#在xyz之间无限循环
X
Y
Z
X
Y
Z
X

(4) accumulate(Iterable object[, function]) (applicable to python3)

The accumulate iterator will return the cumulative sum result, or if two parameters are passed in, the result of the cumulative calculation by the passed function. The default setting is addition

Here, we imported accumulate, and then passed in 10 numbers, 0-9. The iterator accumulates the incoming numbers in sequence, so the first is 0, the second is 0+1, the third is 1+2, and so on.

Now we import the operator module, and then add it:

 >>> from itertools import accumulate
 >>> list(accumulate(range(10)))
 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

Here we pass the numbers 1-4 into the accumulate iterator. We also pass in a function: operator.mul, which multiplies the received parameters.

So each iteration, the iterator will replace division with multiplication (1×1=1, 1×2=2, 2×3=6, and so on)

 from itertools import accumulate
 import operator
 >>> list(accumulate(range(1, 6), operator.mul))
 [1, 2, 6, 24, 120]

(5) chain (* iterable object)

chain can concatenate a group of iteration objects to form a larger iterator:

from itertools import chain
for c in chain(['a','b','cd'],['ef',123],'XYZ'):
    print c

#输出
a
b
cd
ef
123
X
Y
Z

#备注类似于多个list叠加
mm = ['a','b','cd'] + ['ef',123] + ['X','Y','Z']

(6)groupby

Pick out adjacent duplicate elements in the iterator and put them together.

from itertools import groupby

for key, group in groupby('AAABBBCCAAA'):
    print key,list(group)

#输出
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108624203