问题
I have a question about doing permutations with an ordering constraint in python. For the problem an illustration of the issue may be best
Column 1 | Column 2 | Column 3
1 | a | !
2 | b | @
3 | c | #
Now I would like to generate all possible permutations keeping the column ordering such that column 1, before column 2 before column 3, for N-columns
1-a-!
1-a-@
1-a-#
1-b-!
1-b-@
1-b-#
... etc
You can clearly do this by writing nested loops, but I was curious if there was a pythonic way to do this.
回答1:
You're looking for a Cartesian product, not permutations. For that, we have itertools.product
.
import itertools
columns = [
['1', '2', '3'],
['a', 'b', 'c'],
['!', '@', '#']
]
result = ['-'.join(thing) for thing in itertools.product(*columns)]
And so, we have result
:
['1-a-!', '1-a-@', '1-a-#', '1-b-!', '1-b-@', '1-b-#', '1-c-!', '1-c-@', '1-c-#',
'2-a-!', '2-a-@', '2-a-#', '2-b-!', '2-b-@', '2-b-#', '2-c-!', '2-c-@', '2-c-#',
'3-a-!', '3-a-@', '3-a-#', '3-b-!', '3-b-@', '3-b-#', '3-c-!', '3-c-@', '3-c-#']
As you can see, itertools.product
also preserves ordering within each argument, so that !
precedes @
precedes #
and so forth, in case you also need that.
By the way, the *
in itertools.product(*columns)
is an argument unpacking operator.
来源:https://stackoverflow.com/questions/26874698/ordered-column-constrained-permutations-python