The most efficient way to create all the possible combinations of four lists in Python?

I have four different lists. headers, descriptions, short_descriptions, And misc. I want to combine them into all possible printing methods:

header\n
description\n
short_description\n
misc

as if I had (I skip short_description and miscellaneous in this example for obvious reasons)

headers = ['Hello there', 'Hi there!']
description = ['I like pie', 'Ho ho ho']
...

I want it printed as:

Hello there
I like pie
...

Hello there
Ho ho ho
...

Hi there!
I like pie
...

Hi there!
Ho ho ho
...

What would you say is the best / cleanest / most efficient way to do this? Is for-nesting the only way?

+5
source share
5 answers
+10
source
import itertools

headers = ['Hello there', 'Hi there!']
description = ['I like pie', 'Ho ho ho']

for p in itertools.product(headers,description):
    print('\n'.join(p)+'\n')
+4

:

for h, d in ((h,d) for h in headers for d in description):
    print h
    print d
+3

itertools, .

0
source
>>> h = 'h1 h2 h3'.split()
>>> h
['h1', 'h2', 'h3']
>>> d = 'd1 d2'.split()
>>> s = 's1 s2 s3'.split()
>>> lists = [h, d, s]
>>> from itertools import product
>>> for hds in product(*lists):
    print(', '.join(hds))

h1, d1, s1
h1, d1, s2
h1, d1, s3
h1, d2, s1
h1, d2, s2
h1, d2, s3
h2, d1, s1
h2, d1, s2
h2, d1, s3
h2, d2, s1
h2, d2, s2
h2, d2, s3
h3, d1, s1
h3, d1, s2
h3, d1, s3
h3, d2, s1
h3, d2, s2
h3, d2, s3
>>> 
0
source

All Articles