Most efficent way to create all possible combinations of four lists in Python?
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
...
开发者_如何学Python
What would you say is the best/cleanest/most efficent way to do this? Is for
-nesting the only way to go?
Is this what you're looking for? http://docs.python.org/library/itertools.html#itertools.product
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')
A generator expression to do that:
for h, d in ((h,d) for h in headers for d in description):
print h
print d
Have a look to the itertools module, it contains functions to get combinations and permutations from any iterables.
>>> 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
>>>
精彩评论