I have two lists like:
list1 = ['square','circle','triangle'] list2 = ['red','green']
How can I create all permutations of these lists, like this:
[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'trianglered', 'trianglegreen', 'redtriangle', 'greentriangle' ]
Can I use itertools
for this?
The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.
Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!
perm() function in Python is used to return the number of permutations of k items from a group of n items, i.e., it helps us figure out the number of ways in which we can choose k items from n items with order and without repetition.
You want the itertools.product
method, which will give you the Cartesian product of both lists.
>>> import itertools >>> a = ['foo', 'bar', 'baz'] >>> b = ['x', 'y', 'z', 'w'] >>> for r in itertools.product(a, b): print r[0] + r[1] foox fooy fooz foow barx bary barz barw bazx bazy bazz bazw
Your example asks for the bidirectional product (that is, you want 'xfoo' as well as 'foox'). To get that, just do another product and chain the results:
>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)): ... print r[0] + r[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With