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

前端 未结 4 499
别跟我提以往
别跟我提以往 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:05

    Using numpy

    import numpy as np
    from random import shuffle
    A = np.ones(7, dtype=np.int)          // [1 1 1 1 1 1 1] and data-type as integer
    B = np.zeros(3, dtype=np.int)         // [0 0 0] and data-type as integer
    C = np.concatenate((A, B), axis = 0)  // [1 1 1 1 1 1 1 0 0 0]
    shuffle(C)                            // [1 0 0 1 1 1 1 0 1 1]
    print C
    
    0 讨论(0)
  • 2021-01-16 17:15

    I like the shuffle() approach in the other answers; however, there is another way that uses fewer calls to the random number generator. Start with a list of zeros. Then use sample() to pick the 7 indicies that should be set to ones:

    >>> from random import sample
    >>> result = [0] * 10
    >>> for i in sample(range(10), k=7):
            result[i] = 1
    
    >>> result
    [1, 0, 1, 1, 0, 1, 1, 1, 1, 0]
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2021-01-16 17:24

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

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

    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, 0, 0, 1, 1, 1]

    0 讨论(0)
提交回复
热议问题