0

I have REST API that receive arbitrary data which I sort and convert it into list of lists, e.g.

attributes = [ ['nike', 'adidas', 'salmon'], ['38'], ['blue', 'grey'] ]

What I want is to create new list of lists that each element in sub-lists mapped uniquely with others, like:

paths = [ ['nike', '38', 'blue'], 
          ['nike', '38', 'grey'],
          ['adidas', '38', 'blue'], 
          ['adidas', '38', 'grey'],
          ['salmon', '38', 'blue'], 
          ['salmon', '38', 'grey'] ]

I appreciate your answers and suggestions to achieve that in most possible efficient way.

Wadhah Sky
  • 90
  • 1
  • 8
  • 2
    You are looking for Cartesian product. See https://stackoverflow.com/questions/533905/how-to-get-the-cartesian-product-of-multiple-lists – montardon Mar 02 '23 at 20:01
  • Does this answer your question? [permutations of two lists in python](https://stackoverflow.com/questions/1953194/permutations-of-two-lists-in-python) – match Mar 02 '23 at 20:03
  • @montardon Thanx for your response, it's the right solution. – Wadhah Sky Mar 02 '23 at 21:02
  • @match Thanx for your suggestion, but it's look like **`itertools.product`** the right solution. – Wadhah Sky Mar 02 '23 at 21:05

1 Answers1

1

As comments suggest, you can use product function from itertools lib.

>>> from itertools import product
>>> attributes = [ ['nike', 'adidas', 'salmon'], ['38'], ['blue', 'grey'] ]
>>> product(*attributes)
<itertools.product object at 0x7fba3ca3a080>
>>> set(product(*attributes))
{('adidas', '38', 'grey'), ('salmon', '38', 'grey'), ('nike', '38', 'blue'), ('adidas', '38', 'blue'), ('salmon', '38', 'blue'), ('nike', '38', 'grey')}

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34