CB001
CB001

Reputation: 21

Python itertools' permutations() usage for several arrays

I'm constructing dictionaries lists in Python, with aim to iterate through each one individually and concatenate all different combinations. There are three different components to each "product" in a dictionary list:

1) a letter, e.g. 'A' (first part of the product code, unique to each product entry). Let's say the range here is:

['A', 'B', 'C']

2) a letter and number, e.g. 'S2' (2nd part, has several variations...might be 'D3' or 'E5' instead)

3) a period ('.') and a letter, e.g. '.X' (3rd part, unique to each product entry). Let's say the range here is:

['.X', '.Y', '.Z']

Since the 2nd part listed above has the most variations, my starting assumption is to construct dicts lists with the 1st and 3rd parts together, in order to reduce the number of different listsdicts, since they are uniquely paired, e.g. 'A.Z'...but, I would still need to split each entry then insert the 2nd part, between them, via some 'concatenate' command. So, question is: if I have another dict list with all variations of the 2nd part, what function(s) should I use to construct all variants of a product?

The total combination of examples:

ListOne = ['A', 'B', 'C']
ListTwo = ['D3', 'D4', 'D5', 'E3', 'E4', 'E5']
ListThr = ['.X', '.Y', '.Z']

I need to create new dicts lists as concatenations of all three dicts lists, e.g. 'AD3.X', but there are no variants for ListOne vs ListThr, it will always be 'A' matched to '.X' or 'B' and 'C' matched to '.Y'...ListTwo products concatenated between ListOne and ListThr products will need to be iterated so all possible combinations are output as a new dict list e.g.

ListOneNew = ['AD3.X', 'AD4.X', AD5.X', 'AE3.X', 'AE4.X', 'AE5.X']
ListTwoNew = ['BD3.Y', 'BD4.Y', 'BD5.Y', <and so on...>]

For simplicity's sake, should the script have a merged version of ListOne and ListThr e.g.

List = ['A.X', 'B.X', 'C.Z']

and then split & concatenate with ListTwo products, or just have three Lists and concatenate from there?

Upvotes: 0

Views: 149

Answers (2)

Anil_M
Anil_M

Reputation: 11453

With list comprehension

final = sorted([a+b+c for c in DictThr for b in DictTwo for a in DictOne])

Upvotes: 1

Bohdan
Bohdan

Reputation: 581

from itertools import product

result = [a[0] + a[1] + a[2] for a in list(product(DictOne, DictTwo, DictThr))]

Upvotes: 1

Related Questions