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

如何在Python中生成指定1出现次数的0-1随机整数数组?

生成指定1的出现次数的0-1随机数组

你可以通过两种简洁的numpy方法实现需求,以下是针对20个元素、5个1的示例代码:

方法1:随机指定位置赋值1

先创建全0数组,再随机挑选指定数量的位置设置为1:

import numpy as np

total_elements = 20
ones_count = 5

num_samp = np.zeros(total_elements, dtype=int)
# 随机选择不重复的索引位置
selected_indices = np.random.choice(total_elements, ones_count, replace=False)
num_samp[selected_indices] = 1

方法2:构造数组后打乱顺序

先拼接出包含指定数量1和0的数组,再随机打乱顺序:

import numpy as np

total_elements = 20
ones_count = 5

# 拼接1和0的数组
num_samp = np.concatenate([np.ones(ones_count, dtype=int), np.zeros(total_elements - ones_count, dtype=int)])
# 原地打乱数组
np.random.shuffle(num_samp)

两种方法都能保证数组中恰好有指定数量的1,其余为0,且元素位置完全随机。你只需要修改total_elements(总元素数)和ones_count(1的个数)即可适配不同需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:25:34