Play Python3 built-in module of a random stochastic method flowers Summary

Outline

randomPython is a random number associated with the module, which is essentially a pseudo-random number generator, we can use randomblock generated based on a variety of different random numbers, and random number based on the operand.

Generates a random number associated

Generating a floating point number between 0 and 1

import random
r = random.random()
print(r)
r = random.random()
print(r)

Sample results:

0.9928249533693085
0.474901555446297

Generating a floating point number in the specified range

import random
r = random.uniform(1, 100)
print(r)
r = random.uniform(100, 1)
print(r)

Sample results:

69.0347778479432
3.2085981780335118

That range can be placed at both ends of the random range freely, without big left little to the right.

Generating an integer within the specified range

import random
r = random.randint(1, 100)
print(r)

Sample results:

58

generating a random integer randrange

Using randrangegenerated random sequence is then incremented from the sequence returns an integer

import random
# 0 - 100 随机序列
r = random.randrange(101)
print(r)
# 10 - 100 随机序列
r = random.randrange(10, 101)
print(r)
# 10 - 100 并且步进(间隔)为3 的 随机序列
r = random.randrange(10, 101, 3)
print(r)

Sample results:

52
60
46

Related processing sequence

Acquiring a random element from the sequence

Use random.choice(iter)from an arbitrary sequence, such as a list, tuples, dictionaries element libitum

import random
S = 'I like Python'
# 生成一个列表
L = S.split(' ')
print(L)
r = random.choice(L)
print(r)

Scramble sequence elements arranged in

Using random.shuffle(iter)the original arrangement of elements in the sequence upset

import random
S = 'I like Python'
# 生成一个列表
L = S.split(' ')
print(L)
random.shuffle(L)
print(L)

Sample results:

['I', 'like', 'Python']
['like', 'Python', 'I']

Acquiring a plurality of elements from a random sequence

Using random.sample()sequence specified random number acquisition element, and returns the sequence specified length, it does not change the original sequence

# 生成一个递增序列
L = range(11)
rs = random.sample(L, 4)
print(rs)

Sample results:

[1, 0, 10, 7]

We will certainly encounter many difficulties when learning python, as well as the pursuit of new technologies, here's what we recommend learning Python buckle qun: 784758214, here is the python learner gathering place! ! At the same time, he was a senior development engineer python, python script from basic to web development, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Daily share some methods of learning and the need to pay attention to small details

Click: Python technology sharing

Guess you like

Origin blog.csdn.net/zhizhun88/article/details/91464665