排序的列约束置换的Python [英] Ordered Column Constrained Permutations Python

查看:182
本文介绍了排序的列约束置换的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样做的排列在Python中的顺序约束的问题。对于该问题的问题的示图可能是最好的

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 | #

现在我想生成所有可能的排列保持列的顺序,使得第1列,列前3列2之前,对于N-列

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-#

...等

您可以清楚地做到这一点通过编写嵌套循环,但我很好奇,如果有一个Python化的方式来做到这一点。

You can clearly do this by writing nested loops, but I was curious if there was a pythonic way to do this.

推荐答案

您正在寻找一个笛卡尔积,不排列。对于这一点,我们有 itertools.product

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)]

因此​​,我们有结果

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

正如你所看到的, itertools.product 也preserves每个参数中的排序,使 precedes @ precedes 等等,如果你还需要这一点。

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.

顺便说一句,在 * itertools.product(*列)是的参数拆包经营者

By the way, the * in itertools.product(*columns) is an argument unpacking operator.

这篇关于排序的列约束置换的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆