Thursday, September 14, 2017

Python Itertools

ItertoolsExamples

Python Itertools Examples

In [1]:
import itertools

L1 = ['A','B','C']
L2 = range(4)
In [2]:
# permutations

for config in itertools.permutations(L1):
    print(config)
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
In [3]:
# combinations

for config in itertools.combinations(L1, 2):
    print(config)
('A', 'B')
('A', 'C')
('B', 'C')
In [4]:
# product 

for config in itertools.product(L1,L2):
    print(config)
('A', 0)
('A', 1)
('A', 2)
('A', 3)
('B', 0)
('B', 1)
('B', 2)
('B', 3)
('C', 0)
('C', 1)
('C', 2)
('C', 3)
In [5]:
for b in itertools.product([0,1],[0,1],[0,1],[0,1]):
    print(b)
(0, 0, 0, 0)
(0, 0, 0, 1)
(0, 0, 1, 0)
(0, 0, 1, 1)
(0, 1, 0, 0)
(0, 1, 0, 1)
(0, 1, 1, 0)
(0, 1, 1, 1)
(1, 0, 0, 0)
(1, 0, 0, 1)
(1, 0, 1, 0)
(1, 0, 1, 1)
(1, 1, 0, 0)
(1, 1, 0, 1)
(1, 1, 1, 0)
(1, 1, 1, 1)
In [6]:
# cycle (infinite iterator)

x = itertools.cycle(L2)
for i in range(10): 
    print(next(x), end=" ")
0 1 2 3 0 1 2 3 0 1