Generate random integers between 0 and 9

前端 未结 19 1534
无人共我
无人共我 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:14

    I had better luck with this for Python 3.6

    str_Key = ""                                                                                                
    str_RandomKey = ""                                                                                          
    for int_I in range(128):                                                                                    
          str_Key = random.choice('0123456789')
          str_RandomKey = str_RandomKey + str_Key 
    

    Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.

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

    Generating random integers between 0 and 9.

    import numpy
    X = numpy.random.randint(0, 10, size=10)
    print(X)
    

    Output:

    [4 8 0 4 9 6 9 9 0 7]
    
    0 讨论(0)
  • 2020-11-22 16:19

    In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

    >>> import random
    >>> values = list(range(10))
    >>> random.choice(values)
    5
    

    choice also works for one item from a not-continuous sample:

    >>> values = [1, 2, 3, 5, 7, 10]
    >>> random.choice(values)
    7
    

    If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

    >>> import secrets
    >>> values = list(range(10))
    >>> secrets.choice(values)
    2
    
    0 讨论(0)
  • 2020-11-22 16:21

    if you want to use numpy then use the following:

    import numpy as np
    print(np.random.randint(0,10))
    
    0 讨论(0)
  • 2020-11-22 16:23

    The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

    To randomly print an integer in the inclusive range 0-9:

    from secrets import randbelow
    print(randbelow(10))
    

    For details, see PEP 506.

    0 讨论(0)
  • 2020-11-22 16:24
    from random import randint
    
    x = [randint(0, 9) for p in range(0, 10)]
    

    This generates 10 pseudorandom integers in range 0 to 9 inclusive.

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