簡體   English   中英

Python 3.3:列表的所有可能組合

[英]Python 3.3: All possible combinations of list

我有這樣的清單:

[['one', 'two', 'three', ...], ['a', 'b', ...], ['left', 'right'] ...]

我需要創建該項目的所有可能組合,並將其放入字符串中,例如:

"one|a|left"
"one|a|right"
"one|b|left"
"one|b|right"
"two|a|left"
"two|a|right"
"two|b|left"
...

最簡單的方法是什么?

您可以使用itertools.product

from itertools import product
lst = [['one', 'two', 'three'], ['a', 'b'], ['left', 'right']]
print(list(product(*lst)))

驗證它是否滿足您的要求:

[('one', 'a', 'left'), ('one', 'a', 'right'), ('one', 'b', 'left'), ('one', 'b', 'right'), ('two', 'a', 'left'), ('two', 'a', 'right'), ('two', 'b', 'left'), ('two', 'b', 'right'), ('three', 'a', 'left'), ('three', 'a', 'right'), ('three', 'b', 'left'), ('three', 'b', 'right')]

要生成所需的字符串,您需要進行以下描述:

["|".join([p, q, r]) for p, q, r in product(*lst)]

輸出:

['one|a|left',
 'one|a|right',
 'one|b|left',
 'one|b|right',
 'two|a|left',
 'two|a|right',
 'two|b|left',
 'two|b|right',
 'three|a|left',
 'three|a|right',
 'three|b|left',
 'three|b|right']

暫無
暫無

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

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