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