Mic*_*hal 0 python list python-3.x
我有这样的列表:
[['one', 'two', 'three', ...], ['a', 'b', ...], ['left', 'right'] ...]
Run Code Online (Sandbox Code Playgroud)
我需要创建所有可能的项目组合并将其放入字符串中:
"one|a|left"
"one|a|right"
"one|b|left"
"one|b|right"
"two|a|left"
"two|a|right"
"two|b|left"
...
Run Code Online (Sandbox Code Playgroud)
最简单的方法是什么?
你可以使用itertools.product:
from itertools import product
lst = [['one', 'two', 'three'], ['a', 'b'], ['left', 'right']]
print(list(product(*lst)))
Run Code Online (Sandbox Code Playgroud)
验证它是否符合您的要求:
[('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')]
Run Code Online (Sandbox Code Playgroud)
要生成您描述的所需字符串:
["|".join([p, q, r]) for p, q, r in product(*lst)]
Run Code Online (Sandbox Code Playgroud)
输出:
['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']
Run Code Online (Sandbox Code Playgroud)