Generate random integers between 0 and 9

前端 未结 19 1532
无人共我
无人共我 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:05
    >>> import random
    >>> random.randrange(10)
    3
    >>> random.randrange(10)
    1
    

    To get a list of ten samples:

    >>> [random.randrange(10) for x in range(10)]
    [9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
    
    0 讨论(0)
  • 2020-11-22 16:07

    This is more of a mathematical approach but it works 100% of the time:

    Let's say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

    num = (b-a)*random.random() + a;

    Of course, you can generate more numbers.

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

    While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):

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

    For clarity, here we demonstrate how to get multiple random integers.

    Given

    >>> import random
    
    
    lo = 0
    hi = 10
    size = 5
    

    Code

    Multiple, Random Integers

    # A
    >>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
    [5, 6, 1, 3, 0]
    

    # B
    >>> [random.randint(lo, hi) for _ in range(size)]
    [9, 7, 0, 7, 3]
    

    # C
    >>> [random.randrange(lo, hi) for _ in range(size)]
    [8, 3, 6, 8, 7]
    

    # D
    >>> lst = list(range(lo, hi))
    >>> random.shuffle(lst)
    >>> [lst[i] for i in range(size)]
    [6, 8, 2, 5, 1]
    

    # E
    >>> [random.choice(range(lo, hi)) for _ in range(size)]
    [2, 1, 6, 9, 5]
    

    Sample of Random Integers

    # F
    >>> random.choices(range(lo, hi), k=size)
    [3, 2, 0, 8, 2]
    

    # G
    >>> random.sample(range(lo, hi), k=size)
    [4, 5, 1, 2, 3]
    

    Details

    Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

    • A: random.random returns a random float in the range [0.0, 1.0)
    • B: random.randint returns a random integer N such that a <= N <= b
    • C: random.randrange alias to randint(a, b+1)
    • D: random.shuffle shuffles a sequence in place
    • E: random.choice returns a random element from the non-empty sequence
    • F: random.choices returns k selections from a population (with replacement, Python 3.6+)
    • G: random.sample returns k unique selections from a population (without replacement):2

    See also R. Hettinger's talk on Chunking and Aliasing using examples from the random module.

    Here is a comparison of some random functions in the Standard Library and Numpy:

    | | random                | numpy.random                     |
    |-|-----------------------|----------------------------------|
    |A| random()              | random()                         |
    |B| randint(low, high)    | randint(low, high)               |
    |C| randrange(low, high)  | randint(low, high)               |
    |D| shuffle(seq)          | shuffle(seq)                     |
    |E| choice(seq)           | choice(seq)                      |
    |F| choices(seq, k)       | choice(seq, size)                |
    |G| sample(seq, k)        | choice(seq, size, replace=False) |
    

    You can also quickly convert one of many distributions in Numpy to a sample of random integers.3

    Examples

    >>> np.random.normal(loc=5, scale=10, size=size).astype(int)
    array([17, 10,  3,  1, 16])
    
    >>> np.random.poisson(lam=1, size=size).astype(int)
    array([1, 3, 0, 2, 0])
    
    >>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
    array([1, 3, 1, 5, 1])
    

    1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al. 2@prashanth mentions this module showing one integer. 3Demonstrated by @Siddharth Satpathy

    0 讨论(0)
  • 2020-11-22 16:10
    import random
    print(random.randint(0,9))
    

    random.randint(a, b)
    

    Return a random integer N such that a <= N <= b.

    Docs: https://docs.python.org/3.1/library/random.html#random.randint

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

    I would try one of the following:

    1.> numpy.random.randint

    import numpy as np
    X1 = np.random.randint(low=0, high=10, size=(15,))
    
    print (X1)
    >>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])
    

    2.> numpy.random.uniform

    import numpy as np
    X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)
    
    print (X2)
    >>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])
    

    3.> random.randrange

    from random import randrange
    X3 = [randrange(10) for i in range(15)]
    
    print (X3)
    >>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]
    

    4.> random.randint

    from random import randint
    X4 = [randint(0, 9) for i in range(0, 15)]
    
    print (X4)
    >>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]
    

    Speed:

    np.random.randint is the fastest, followed by np.random.uniform and random.randrange. random.randint is the slowest.

    ► Both np.random.randint and np.random.uniform are much faster (~8 - 12 times faster) than random.randrange and random.randint .

    %timeit np.random.randint(low=0, high=10, size=(15,))
    >> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
    >> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    %timeit [randrange(10) for i in range(15)]
    >> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    %timeit [randint(0, 9) for i in range(0, 15)]
    >> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

    Notes:

    1.> np.random.randint generates random integers over the half-open interval [low, high).

    2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

    3.> random.randrange(stop) generates a random number from range(start, stop, step).

    4.> random.randint(a, b) returns a random integer N such that a <= N <= b.

    5.> astype(int) casts the numpy array to int data type.

    6.> I have chosen size = (15,). This will give you a numpy array of length = 15.

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

    From the documentation page for the random module:

    Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

    random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.

    >>> import string
    >>> string.digits
    '0123456789'
    >>> import random
    >>> random.SystemRandom().choice(string.digits)
    '8'
    >>> random.SystemRandom().choice(string.digits)
    '1'
    >>> random.SystemRandom().choice(string.digits)
    '8'
    >>> random.SystemRandom().choice(string.digits)
    '5'
    

    Instead of string.digits, range could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.

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