Generate random integers between 0 and 9

前端 未结 19 1533
无人共我
无人共我 2020-11-22 15:37

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4

相关标签:
19条回答
  • 2020-11-22 16:24

    random.sample is another that can be used

    import random
    n = 1 # specify the no. of numbers
    num = random.sample(range(10),  n)
    num[0] # is the required number
    
    0 讨论(0)
  • 2020-11-22 16:26

    Try:

    from random import randrange
    print(randrange(10))
    

    Docs: https://docs.python.org/3/library/random.html#random.randrange

    0 讨论(0)
  • 2020-11-22 16:26

    Try this through random.shuffle

    >>> import random
    >>> nums = range(10)
    >>> random.shuffle(nums)
    >>> nums
    [6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
    
    0 讨论(0)
  • 2020-11-22 16:28

    Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:

    import numpy as np   
    np.random.randint(10, size=(1, 20))
    

    You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).

    array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])
    
    0 讨论(0)
  • 2020-11-22 16:28

    Best way is to use import Random function

    import random
    print(random.sample(range(10), 10))
    

    or without any library import:

    n={} 
    for i in range(10):
        n[i]=i
    
    for p in range(10):
        print(n.popitem()[1])
    

    here the popitems removes and returns an arbitrary value from the dictionary n.

    0 讨论(0)
  • 2020-11-22 16:29

    OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined defined class.

    The following simulates 12 outcomes of the distribution.

    import openturns as ot
    points = [[i] for i in range(10)]
    distribution = ot.UserDefined(points) # By default, with equal weights.
    for i in range(12):
        x = distribution.getRealization()
        print(i,x)
    

    This prints:

    0 [8]
    1 [7]
    2 [4]
    3 [7]
    4 [3]
    5 [3]
    6 [2]
    7 [9]
    8 [0]
    9 [5]
    10 [9]
    11 [6]
    

    The brackets are there becausex is a Point in 1-dimension. It would be easier to generate the 12 outcomes in a single call to getSample:

    sample = distribution.getSample(12)
    

    would produce:

    >>> print(sample)
         [ v0 ]
     0 : [ 3  ]
     1 : [ 9  ]
     2 : [ 6  ]
     3 : [ 3  ]
     4 : [ 2  ]
     5 : [ 6  ]
     6 : [ 9  ]
     7 : [ 5  ]
     8 : [ 9  ]
     9 : [ 5  ]
    10 : [ 3  ]
    11 : [ 2  ]
    

    More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html

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