简体   繁体   中英

Python 3.3: All possible combinations of list

I have list like this:

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

and I need to create all possible combinations of that items and put it into string like:

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

what is the easiest way to do it?

You can use itertools.product :

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

Verify that it does what you want:

[('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')]

To produce the desired strings you described:

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

Output:

['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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM