Get the cartesian product of a series of lists?
itertools.product
Available from Python 2.6.
import itertools
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
for element in itertools.product(*somelists):
print(element)
Which is the same as,
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
print(element)
Cartesian product of two lists in python
Do a list comprehension, iterate over both the lists and add the strings, like
list3 = [i+str(j) for i in list1 for j in list2]
How to create lists from a cartesian product of two string lists
Try this, use the itertools library. There is a function called product that gets you a cartesian product.
import itertools
x = ['parking_meter', 'sink', 'teddy_bear']
y = ['sail', 'fill', 'fly', 'greet', 'hit', 'hose', 'hunt', 'install', 'kick', 'launch', 'move', 'pick', 'repair', 'sit_at', 'squeeze', 'stab', 'straddle', 'talk_on']
Then you can do this 2-liner, (because the product function returns a tuple but you require a list)
z = list(itertools.product(x,y))
z = [list(z) for z in z]
Or this 1-liner,
z = [list(tup) for tup in list(itertools.product(x, y))]
Then I,
print (z)
Which gives me
[['parking_meter', 'sail'],
['parking_meter', 'fill'],
['parking_meter', 'fly'],
['parking_meter', 'greet'],
['parking_meter', 'hit'],
['parking_meter', 'hose'],
['parking_meter', 'hunt'],
['parking_meter', 'install'],
['parking_meter', 'kick'],
['parking_meter', 'launch'],
['parking_meter', 'move'],
['parking_meter', 'pick'],
['parking_meter', 'repair'],
['parking_meter', 'sit_at'],
['parking_meter', 'squeeze'],
['parking_meter', 'stab'],
['parking_meter', 'straddle'],
['parking_meter', 'talk_on'],
['sink', 'sail'],
['sink', 'fill'],
['sink', 'fly'],......
How to join strings from a Cartesian product of two lists
You can try list comprehension with two nested for loop over numbers
and then letters
:
print([l+n for n in numbers for l in letters])
# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']
You can also use nested for loop:
out = []
for n in numbers:
for l in letters:
out.append(l+n)
print(out)
# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']
For more details on list comprehension, see either the doc or this related topic.
Getting the cartesian product of two lists as a list-of-lists
well, you just needed one more level of list.
deck = [[x+y for x in value] for y in deck_types]
Cartesian product of two lists in python letters and numbers
You were close:
[[l,n] for l in list1 for n in list2]
Improving the performance of cartesian product of multiple lists
A few comments:
If you think about it, what
car_multiple_sets
is doing is iterating on its parameterlists
. You're doing that using recursion, but iterating on a list can also be done with afor
-loop. And it so happens that recursion is somewhat slow and memory-inefficient in python, sofor
-loops are preferable.You don't need to convert to
str
to group the ints together. You can usetuples
. That's precisely what they're for. Replacestr(x)+str(y)
with(x,y)
to get a pair of two integers instead of a string.
def car_two_sets(a, b, unpack=False):
if unpack:
return [(*x, y) for x in a for y in b]
else:
return [(x, y) for x in a for y in b]
def car_multiple_sets(lists):
if len(lists) == 0:
return [()] # empty Cartesian product has one element, the empty tuple
elif len(lists) == 1:
return list(zip(lists[0])) # list of "1-uples" for homogeneity
else:
result = car_two_sets(lists[0], lists[1])
for l in lists[2:]:
result = car_two_sets(result, l, unpack=True)
return result
print( car_multiple_sets((range(3), 'abc', range(2))) )
# [(0, 'a', 0), (0, 'a', 1), (0, 'b', 0), (0, 'b', 1), (0, 'c', 0), (0, 'c', 1),
# (1, 'a', 0), (1, 'a', 1), (1, 'b', 0), (1, 'b', 1), (1, 'c', 0), (1, 'c', 1),
# (2, 'a', 0), (2, 'a', 1), (2, 'b', 0), (2, 'b', 1), (2, 'c', 0), (2, 'c', 1)]
Most Pythonic way to form cartesian product of two lists of strings
You can do this using itertools.product
>>> from itertools import product
>>> l1 = ["Col1", "Col2", "Col3"]
>>> l2 = ["_ad1", "_ad2"]
>>> list(elem[0] + elem[1] for elem in product(l1, l2))
['Col1_ad1', 'Col1_ad2', 'Col2_ad1', 'Col2_ad2', 'Col3_ad1', 'Col3_ad2']
Related Topics
How to Split a Dos Path into Its Components in Python
How to Run Python Code from Sublime Text 2
Turn a String into a Valid Filename
Creating a Pandas Dataframe from a Numpy Array: How to Specify the Index Column and Column Headers
How to Get Indices of a Sorted Array in Python
How to Write a Multidimensional Array to a Text File
What Does It Mean to "Call" a Function in Python
Zip Variable Empty After First Use
How to Locate Element of Credit Card Number Using Selenium Python
How to Add an Image or Icon to a Button Rectangle in Pygame
Why Is It String.Join(List) Instead of List.Join(String)
Purpose of "%Matplotlib Inline"
How to Install Psycopg2 with "Pip" on Python
Making Python Loggers Output All Messages to Stdout in Addition to Log File