Python random function common method + Example Encyclopedia

All methods resulting dir random function:

Enter the interactive mode: >>> dir (random) Enter

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

Conventional method (in bold) + Example

  • #random () method returns a real number randomly generated, it is in the range [0,1)

>>> import random

  • # Implement a random integer number from 1 to 100, a value is obtained

>>> random.randint(1,100)

83

  • # Achieve random floating point number between 0-1, a value is obtained

>>> random.random()

0.23697707021418746

  • # 100-120 implement floating point random, a value is obtained

>>> (random.random()*21)+100

118.87488295506476

  • # 100-101.99 achieve random floating point interval may not be an integer, a value is obtained

>>> random.uniform(100,101.99)

100.39827372316675

  • # Implemented sequence (sequence type: list, tuple, string) randomly an element, resulting in a sequence of elements

>>> random.choice("tomorrow")

'w'

  • # Interval from 1-100 to achieve a random integer, corresponding to the [1,3,5,7, ..., 99] acquires a random number sequence, a numerical value is obtained

>>> random.randrange (1,100,2)

7

  • # The sequence order of the elements disrupted, is obtained i.e. a new list element of the list is modified

>>> a=[1,3,5,7,9]

>>> random.shuffle(a)

>>> a

[9, 7, 1, 5, 3]

  • # Sequence of random fragments of a specified length taken to obtain a list is not modified, but the original sequence,

>>> a=[1,3,5,7,9]

>>> random.sample(a,2)

[5, 1]

>>> random.sample(a,2)

[3, 7]

Guess you like

Origin blog.csdn.net/chang_jinling/article/details/81260155