【问题标题】:How to generate all 2d arrays of row permutations in Python?如何在 Python 中生成所有二维行排列数组?
【发布时间】:2020-12-06 10:39:15
【问题描述】:

有一个数组:

[[1,2],
 [3,4]]

如何生成所有行排列的数组列表? 我希望得到如下结果:

[[[1,2],
  [3,4]],
 [[1,2],
  [4,3]],
 [[2,1],
  [4,3]],
 [[2,1],
  [3,4]]]

重要的是第一行的值不要与第二行或任何其他行的值混合。

【问题讨论】:

    标签: arrays python-3.x numpy combinations


    【解决方案1】:

    以下适用于 n 行的唯一区别是您获得了一个元组列表:

    from itertools import product, permutations
    
    [*product(*[permutations(row) for row in matrix])]
    # For no duplicates:
    [*product(*[set(permutations(row)) for row in matrix])]
    

    【讨论】:

    • 如果我的输入数组有 'n' 行怎么办?
    • @PoczciwyKorsarz 正是我想知道的) - 见编辑。
    • 非常感谢您的帮助。因为我的 NumPy 数组是布尔值(有很多重复)并且我想取回 NumPy 数组,所以我将您的代码稍微更改为以下形式: allPossibleMatrices = [np.array(_) for _ in [*product (*[set(permutations(row)) for row in matrix2d])]]
    • @PoczciwyKorsarz 好的 - 如果您使用 numpy,只需 np.array([*product(*[permutations(row) for row in matrix])]) 也可以)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2017-03-27
    • 1970-01-01
    • 2015-12-23
    • 2011-01-08
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多