Insert in a list random of 0 and 1 with a certain number of 1's

前端 未结 4 501
别跟我提以往
别跟我提以往 2021-01-16 16:43

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.

For example, I want a list of 10

4条回答
  •  攒了一身酷
    2021-01-16 17:20

    An approach not using random.shuffle:

    import random
    random.sample([0]*3 + [1]*7, 10) # [1, 1, 1, 1, 0, 0, 0, 1, 1, 1]
    

提交回复
热议问题