Hello everyone , Here is Python Programmer Wanfeng .
Recently I saw a on the Internet python The interview topic of : How to use Python Generate 1 Million cell phone numbers ?
When I first saw it, I thought , This is not easy ? direct random.randint(1,999999999999)
Just a matter of .
But I found the mistake immediately : This is the generation 1-99999999 Random number between , May be 1, It could be 666.
But the phone number is 11 Bit , And before 3 Bit has only the specified number segment , such as 135、136. direct random.randint(1,999999999999)
This is not qualified .
So how to generate ? So here's the code :
import randomdef create_phone_num(num): all_phone_nums = set() # Store the generated phone number while True: # because set It will automatically go heavy , So the loop generates phone numbers , Until it's equal to num Number stop start = random.choice(['135', '136', '137']) # Before storage 3 Number segment of bit , Choose one at random end = ''.join(random.sample(string.digits, 8)) # After random generation 8 Digit number all_phone_nums.add(f'{start}{end}') # Before splicing 3 Position and back 8 position if len(all_phone_nums) >= num: # If the number of numbers equals num, Then stop breakphone_num(10000 * 10000)
After writing the code this time, I found , original Python Of random There are so many easy-to-use methods of generating random numbers .
I sorted them all out , Today we will learn together ~
If there are omissions or errors , Welcome to give more advice ~
In the first line of the code above :import random
, We imported random This standard library .
This library has only one file :random.py
, The structure of this document is mainly divided into 3 individual
part ( As shown in the figure below ), Their functions are :
Random(_random.Random)
and SystemRandom(Random)
Random()
_test_generator(n, func, args)
and _test(N=2000)
random.choice
、random.sample
, Specific usage , We will explain in detail next . Next, we will focus on as python Users of , What will we use random
The random number method of , As mentioned above random.py
Page 2 of the document 3 part .
As shown in the code below ,random The methods provided are as follows 22 individual , It is mainly divided into 2 class :
Ordinary users
Common methods , Altogether 12 individual
; Scientific Computing
Common methods , Altogether 10 individual
.For the above 22 A random number method , Here I will focus on the one commonly used by ordinary users 12 A way .
As for the latter 10 A method for scientific calculation , Because it's really profound , I won't waste my time here , Interested students , You can go directly to the math book :《 probability theory 》.
Put this 3 Put them together and say , Because random In essence, it generates pseudo-random numbers , And this 3 A function , It well reflects the characteristics of pseudo-random numbers
Code example :seed
# Appoint seed after , The generated random numbers are the same random.seed(1)print(' random number 1:', random.random())random.seed(1)print(' random number 2:', random.random())# output:# random number 1: 0.13436424411240122# random number 2: 0.13436424411240122
Code example : random.getstate & random.setstate
import randomrandom.seed(42)print(random.sample(range(20), k=10))st = random.getstate() # Take out and generate the last line of code ,random The state of print(random.sample(range(20), k=20)) # print 20random.setstate(st) # Restore the last random state print(random.sample(range(20), k=10)) # print same first 10# output:# [12, 0, 4, 3, 11, 10, 19, 1, 5, 18]# [4, 9, 0, 3, 10, 8, 16, 7, 18, 17, 14, 6, 2, 1, 5, 11, 15, 13, 19, 12]# [4, 9, 0, 3, 10, 8, 16, 7, 18, 17]
Randomly generate one [0,1) The floating point number between
Code example
float = random.random()"""float = 0.123565654548978"""
produce [a,b] A random floating-point number in the range
Code example
float = random.uniform(11,15)"""float = 13.882923467738049"""
Random generation [a,b] An integer in the range .
Code example
int = random.randint(1, 9)"""int = 2"""
Randomly select a data from a non empty sequence and bring it back , The sequence can be list、tuple、str、set.
Code example
str = random.choice(" Programmer Wanfeng original series ")"""str = primary """
Python3.6 Version added . Select randomly from the cluster k Time data , Return a list , You can set weights . Altogether 4 Parameters
Code example
str = [" cheng ", " order ", " member ", " On the evening of ", " Maple "]res = random.choices(str, weights=[0, 0, 1, 0, 0], k=5)""" Because to 【 member 】 This word , adopt weights The parameter adds a special weight :1, Other weights are 0, So no matter how many times you choose randomly , The result is 【 member 】res = [' member ', ' member ', ' member ', ' member ', ' member ']"""
Reference resources range Usage of :
Code example
int = random.randrange(3, 9)"""int = 5"""
Select from the set k Elements , Return a list , Clusters can be list、tuple、str、set.
Code example
str = [" cheng ", " order ", " member ", " On the evening of ", " Maple "]res = random.sample(str, 5)"""res = [' member ', ' order ', ' cheng ', ' Maple ', ' On the evening of ']"""
Disrupt the original ordered set , Be careful : This method does not return a value , It directly changes the order of the original set . So if you want to change tuple This immutable set , Will report a mistake .
Code example
str = [" cheng ", " order ", " member ", " On the evening of ", " Maple ", " Yes ", " along ", " order "]random.shuffle(str)"""str = [' Maple ', ' along ', ' member ', ' order ', ' Yes ', ' On the evening of ', ' order ', ' cheng ']"""
Generate an integer with a specified bit size .
Code example
int = random.getrandbits(8)"""int = 136"""
Although I am Python The programmer , But in the recent development, I found that I didn't master many basic knowledge .
So I decided to start with this one , I decided to take that time to join Python when , The romantic feelings of feeding horses and chopping firewood and facing the sea , Go to the serious in-depth sorting and sharing Python Common knowledge points .
I hope it works for you .