簡體   English   中英

最有效的方法是在Python中創建四個列表的所有可能組合?

[英]Most efficent way to create all possible combinations of four lists in Python?

我有四個不同的列表。 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 -nesting去的唯一途徑?

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

生成器的表達式:

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

看看itertools模塊,它包含從任何迭代中獲得組合和排列的函數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM