如何用Python生成指定数量8的4×4零矩阵及批量生成方法
生成指定含8数量的4×4矩阵
单个矩阵生成(纯Python实现)
无需第三方库,用内置random模块即可完成:
import random def create_4x4_matrix(n): # 初始化4×4全0矩阵 matrix = [[0]*4 for _ in range(4)] # 生成所有可用位置的坐标 all_positions = [(i, j) for i in range(4) for j in range(4)] # 随机挑选n个不重复的位置 selected = random.sample(all_positions, n) # 给选中位置赋值8 for i, j in selected: matrix[i][j] = 8 return matrix # 测试:生成含3个8的矩阵 sample_matrix = create_4x4_matrix(3) for row in sample_matrix: print(row)
单个矩阵生成(NumPy实现,更高效)
如果需要处理大量矩阵,用NumPy会更简洁高效:
import numpy as np def create_4x4_matrix_np(n): matrix = np.zeros((4, 4), dtype=int) # 从16个扁平化位置中随机选n个不重复的索引 indices = np.random.choice(16, size=n, replace=False) matrix.flat[indices] = 8 return matrix.tolist() # 转为列表格式,也可直接返回numpy数组 # 测试 sample_matrix_np = create_4x4_matrix_np(3) for row in sample_matrix_np: print(row)
批量生成矩阵
遍历一组数值,批量生成对应规则的矩阵:
# 要生成的矩阵对应的8的数量列表 target_counts = [2, 4, 6] # 批量生成 batch_matrices = [create_4x4_matrix(count) for count in target_counts] # 输出结果 for idx, (count, mat) in enumerate(zip(target_counts, batch_matrices), 1): print(f"矩阵{idx}(含{count}个8):") for row in mat: print(row) print("-"*20)
关键说明
- 两种实现都通过无重复随机选择确保每个8的位置不重叠,避免同一位置被多次赋值。
- 如果需要可复现的随机结果,可以在代码开头添加
random.seed(固定值)(纯Python)或np.random.seed(固定值)(NumPy)。
内容的提问来源于stack exchange,提问作者rpickmans
相关产品推荐
相关产品推荐

