-2

I want to get a list of ('A_1','A_2','B_1','B_2','C_1','C_2'), with something like '_'.join() and [(x, y) for x in ['A','B','C'] for y in [1,2]].

How to write this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Galaxy
  • 1,862
  • 1
  • 17
  • 25
  • @jonrsharpe Does this edit makes the question not a duplicate ? – Galaxy May 27 '19 at 08:27
  • 1
    Nope; you're asking two questions (how to get pairs, how to format pairs) both of which are already covered on SO and elsewhere. You need to decompose your problems and do research around the parts. – jonrsharpe May 27 '19 at 08:29

1 Answers1

3

Use itertools.product:

On python3.6+

import itertools
letters = ['A','B','C']
nums = [1, 2]
result = [f"{l}_{n}" for l, n in itertools.product(letters, nums)]

Or in lower python versions:

result = ["{}_{}".format(l, n) for l, n in itertools.product(letters, nums)]

Output:

>>> result
['A_1', 'A_2', 'B_1', 'B_2', 'C_1', 'C_2']
Netwave
  • 40,134
  • 6
  • 50
  • 93