在Python中创建四个列表的所有可能组合的最有效方法?

时间:2010-03-05 22:15:29

标签: python algorithm

我有四个不同的名单。 headersdescriptionsshort_descriptionsmisc。我想将这些结合到所有可能的打印方式中:

header\n
description\n
short_description\n
misc

就好像我曾经(因为显而易见的原因,我在这个例子中跳过short_description和misc)

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

我希望它打印出来像:

Hello there
I like pie
...

Hello there
Ho ho ho
...

Hi there!
I like pie
...

Hi there!
Ho ho ho
...

你认为最好/最干净/最有效的方法是什么?是for - 筑巢唯一的方法吗?

5 个答案:

答案 0 :(得分:10)

答案 1 :(得分:4)

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')

答案 2 :(得分:3)

要执行此操作的生成器表达式:

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

答案 3 :(得分:0)

查看 itertools 模块,它包含从任何迭代中获取组合和排列的函数。

答案 4 :(得分:0)

>>> 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
>>>