views:

174

answers:

5

I have four different lists. headers, descriptions, short_descriptions and misc. I want to combine these into all the possible ways to print out:

header\n
description\n
short_description\n
misc

like if i had (i'm skipping short_description and misc in this example for obvious reasons)

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

I want it to print out like:

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 efficent way to do this? Is for-nesting the only way to go?

+10  A: 

Is this what you're looking for? http://docs.python.org/library/itertools.html#itertools.product

linked
Damnit, I had been skimming through itertools looking for something that could solve my problem without finding this! Thanks.
Baresi
A: 

Have a look to the itertools module, it contains functions to get combinations and permutations from any iterables.

e-satis
+4  A: 
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')
unutbu
+3  A: 

A generator expression to do that:

for h, d in ((h,d) for h in headers for d in description):
    print h
    print d
Matt Anderson
Nice one! Although this is not as easy to read as the solution using `itertools.product` I can't disagree with one that doesn't require any imports.
jathanism
A: 
>>> 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
>>> 
Paddy3118