You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效生成10行70列布尔矩阵的所有可能组合?

更优实现:用笛卡尔积生成所有布尔矩阵组合

Hey, let's start with a critical reality check first: a 10x70 boolean matrix has 700 elements, each with 2 possible values. That means there are 2^700 total combinations—a number so astronomically large it's way bigger than the estimated number of atoms in the observable universe. If you're planning to actually iterate through all of these, you'll never finish. So first, ask yourself: do you really need every single combination, or just a subset that meets specific criteria?

That said, from a technical standpoint, you absolutely don't need 1400 nested for loops. Python's itertools.product was made exactly for this kind of Cartesian product generation. Here's how to implement it cleanly:

Code Implementation

import itertools

# Define your matrix dimensions
num_rows = 10
num_cols = 70

# Generate all possible 700-length boolean sequences (as tuples)
all_bool_sequences = itertools.product([True, False], repeat=num_rows * num_cols)

# Convert each flat sequence into a 10x70 matrix
for seq in all_bool_sequences:
    # Slice the flat sequence into 10 chunks of 70 elements each
    matrix = [list(seq[i*num_cols : (i+1)*num_cols]) for i in range(num_rows)]
    # Add your logic here (e.g., process, print, or save the matrix)
    # WARNING: This loop will never terminate in practice due to the sheer number of combinations
    print(matrix)

Key Notes

  • itertools.product handles all the nested loop logic under the hood, so you don't have to write hundreds of loops manually. It's efficient and readable.
  • By flattening the matrix into a 1D sequence first, we simplify the combination generation, then convert back to a 2D structure with basic slicing.
  • Again, do not run this full loop in practice. If you only need certain matrices (e.g., those with exactly 50 True values, or rows that meet a condition), add a filter before converting to a matrix to avoid wasting resources on irrelevant combinations.

For example, if you only want matrices where the last column is all True:

for seq in all_bool_sequences:
    # Check if every 70th element (last column) is True
    if all(seq[num_cols-1::num_cols]):
        matrix = [list(seq[i*num_cols : (i+1)*num_cols]) for i in range(num_rows)]
        print(matrix)

内容的提问来源于stack exchange,提问作者markop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:23:05