Python生成矩阵的所有可能组合

Python生成矩阵的所有可能组合

本文介绍了Python生成矩阵的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中生成矩阵的所有组合.输入将是两个整数n和m,我需要生成该矩阵的所有可能状态,并使用1和0作为可能的值.

I need to generate all combinations of a matrix in Python. The input will be two integers n and m, and I need to generate all possible states of that matrix with 1 and 0 as possible values.

例如:

n = 3 m = 2
[[0 0 0] [1 0 0] [1 1 0]
 [0 0 0] [0 0 0] [0 0 0]
 [0 0 0],[0 0 0],[0 0 0] . . . . .
]

给定我直到运行时才知道n和m的值,是否有一种干净有效的方法来执行此操作?使用的最大值为n = 16 m = 16.

Is there a clean and efficient way to do this given I will not know the values for n and m until runtime? The highest value used will be n = 16 m = 16.

推荐答案

一种方法是在列表理解中生成所有长度为 m * n 的二进制序列,并将其重塑为(m,n)在每次迭代中形成嵌套列表.

One way is by generating all binary sequences of length m*n in a list comprehension, and reshaping them into a (m,n) shaped nested list on each iteration.

一种生成所有序列的简单方法是,将 01 的笛卡尔乘积与 n * m 重复,将产生 2 ^(m *n)组合:

A simple way to generate all sequences is by taking the cartesian product of 01 with n*m repeats, which will be produce 2^(m*n) combinations:

from itertools import product
m=3
n=3

x = [[list(i[x:x+m]) for x in range(0, len(i), m)] for i in product("01", repeat=m*n)]

输出

[[['0' '0' '0']
  ['0' '0' '0']
  ['0' '0' '0']]

 [['0' '0' '0']
  ['0' '0' '0']
  ['0' '0' '1']]

 [['0' '0' '0']
  ['0' '0' '0']
  ['0' '1' '0']]
 ...

print(len(x))
# 512

这篇关于Python生成矩阵的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:36