Ordered Column Constrained Permutations Python

妖精的绣舞 提交于 2019-12-11 20:12:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!