简体   繁体   English

如何生成大小为 41003 的 0 和 1 数组,并且 1 的数量应该仅为 100?

[英]how to generate an array of 0s and 1s of size 41003 and number of 1s should be 100 only?

I want to generate an array of size 41003 containing 0s and 1s.我想生成一个大小为 41003 的数组,其中包含 0 和 1。 but the number of 1s should be 100. how to do this in python?但是 1 的数量应该是 100。如何在 python 中做到这一点?

I tried to generate using我试图生成使用

np.random.randint(2, size=41003) 

but the number of 1s is not 100.但是 1 的数量不是 100。

Initialize a list with n=41003 zeros.用 n=41003 个零初始化一个列表。 Then use random.sample(range(n), k=100) to generate 100 non repeated random indices on that list.然后使用random.sample(range(n), k=100)在该列表上生成 100 个不重复的随机索引。
Finally, set to 1 the values in the list with those indices.最后,将具有这些索引的列表中的值设置为 1。

from random import sample

n = 41003
values = [0] * n
for i in sample(range(0, n), k=100):
    values[i] = 1

print(values.count(1)) # 100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM