插入一个随机数为0和1且数量为1的列表 [英] Insert in a list random of 0 and 1 with a certain number of 1's

查看:76
本文介绍了插入一个随机数为0和1且数量为1的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成长度为 N 的列表,该列表具有随机的0和1值,但是在列表中随机放入给定数量的1.

How do I generate a list of length N with random 0 and 1 values , but with a given number of 1's put randomly in the list.

例如,我想要一个包含10个元素(0和1)的列表,并且列表中的1的数目为7.

For example, I want a list of 10 elements(0 and 1) and the numbers of 1's in the list to be 7.

我该怎么做?

推荐答案

您可以轻松地使列表具有正确的数字0和1

You can make the list have the right number of 0's and 1's pretty easily

data = [0] * 3 + [1] * 7

,然后使用random.shuffle使其在列表中的位置随机

and then use random.shuffle to make their positions within the list random

from random import shuffle
shuffle(data)
print data

[1,1,0,1,1,1,0,0,1,1,1]

[1, 1, 0, 1, 1, 0, 0, 1, 1, 1]

这篇关于插入一个随机数为0和1且数量为1的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆