Home > database >  Create product of lists, concatenated, in python
Create product of lists, concatenated, in python

Time:03-20

import itertools
x = [[0,0],[1,1]]
list(itertools.product(x,x))

produces

[([0, 0], [0, 0]), ([0, 0], [1, 1]), ([1, 1], [0, 0]), ([1, 1], [1, 1])]

But I'm looking for something that produces

[[0, 0, 0, 0], [0, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]]

CodePudding user response:

itertools.product is giving you that answer, you just have to concatenate the lists

[a   b for a, b in [([0, 0], [0, 0]), ([0, 0], [1, 1]), ([1, 1], [0, 0]), ([1, 1], [1, 1])]]
# [[0, 0, 0, 0], [0, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]]

CodePudding user response:

In that case, you can easily do without using itertools, using list comprehension:

x = [[0, 0], [1, 1]]
output = [a   b for b in x for a in x]
# [[0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [1, 1, 1, 1]]

the equivalent without list comprehension would be:

output = []
for a in x:
    for b in x:
        output.append(a   b)
print(output)

CodePudding user response:

You can use np.reshape if you are considering numpy array.

np.reshape(list(itertools.product(x,x)),(4,4))
Out[28]: 
array([[0, 0, 0, 0],
       [0, 0, 1, 1],
       [1, 1, 0, 0],
       [1, 1, 1, 1]])
  • Related