-7

I have three lists: [A, B, C], [1], [x,y].

How to generate the following with python:

[A,1,x], [A,1,y], [B,1,x], [B,1,y], [C,1,x], [C,1,y]

Paul R
  • 2,631
  • 3
  • 38
  • 72

4 Answers4

2

Here you go:

Z = [['A', 'B', 'C'], [1], ['x', 'y']]

import itertools
for element in itertools.product(*Z):
    print(element)

Result:

('A', 1, 'x')
('A', 1, 'y')
('B', 1, 'x')
('B', 1, 'y')
('C', 1, 'x')
('C', 1, 'y')
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73
1

You can do this easily using a list comprehension:

l1 = ['A', 'B', 'C']
l2 = [1]
l3 = ['x', 'y']

product = [
    [a, b, c]
    for a in l1
    for b in l2
    for c in l3
]
SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
1

Use itertools.product

import itertools
list(itertools.product([A, B, C], [1, 2], [x,y])) 
# provided A, B, C, x, y are variables.
hspandher
  • 15,934
  • 2
  • 32
  • 45
0

To start:

>>> from itertools import product
>>> a = ['A','B']
>>> b = [1,2]
>>> list(product(a, b))
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]

And:

>>> a = ['A','B','C']
>>> b = [1]
>>> c = ['x', 'y']
>>> list(product(a,b,c))
[('A', 1, 'x'), ('A', 1, 'y'), ('B', 1, 'x'), ('B', 1, 'y'), ('C', 1, 'x'), ('C', 1, 'y')]

That is that you want, but please try to search a bit more before to post a question.

Juan Antonio
  • 2,451
  • 3
  • 24
  • 34