passerby51
passerby51

Reputation: 955

Zipping a product of iterators and a count iterator

I am trying to concatenate a count to the product of two iterators as follows:

import itertools
it1 = itertools.product(['A', 'B'], [1, 2, 3])
it2 = itertools.count(1)
list(zip(it1, it2))

This generates the output

[(('A', 1), 1),
 (('A', 2), 2),
 (('A', 3), 3),
 (('B', 1), 4),
 (('B', 2), 5),
 (('B', 3), 6)]

However, what I would like to have is

[('A', 1, 1),
 ('A', 2, 2),
 ('A', 3, 3),
 ('B', 1, 4),
 ('B', 2, 5),
 ('B', 3, 6)]

Upvotes: 1

Views: 45

Answers (1)

Djaouad
Djaouad

Reputation: 22776

You can use a list comprehension to flatten the tuples:

result = [(*i, j) for i, j in zip(it1 , it2)]

print(result)

Output:

[('A', 1, 1),
 ('A', 2, 2),
 ('A', 3, 3),
 ('B', 1, 4),
 ('B', 2, 5),
 ('B', 3, 6)]

Upvotes: 2

Related Questions