current position:Home>Python notes (21): random number module
Python notes (21): random number module
2022-01-30 16:49:59 【A bowl week】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
This module implements pseudo-random number generator of various distributions . For integers , There is a unified choice from the scope . For the sequence , There is a uniform selection of random elements 、 A function used to generate a random arrangement of lists 、 And functions for random sampling without replacement .
Generate random number
random.random()
Method
Returns a randomly generated real number , It's in [0,1) Within the scope of .
Grammatical structure
import random # Import random modular
random.random()
Copy code
random.randint
Method
Grammar format
random.randint(a,b)
Copy code
Function returns a number N ,N by a To b Number between (a <= N <= b), contain a and b
random.uniform
Method
Grammar format
random.uniform(a,b)
Copy code
Function returns a random floating-point number N , When a <= b
when a <= N <= b
, When b < a
when b <= N <= a
.
random.randrange
Method
Grammatical structure
random.randrange(start, stop[, step])
Copy code
- start: Count from start Start . The default is 0 Start . for example randrange(5) Equivalent to range(0, 5);
- stop: Count to stop end , But does not include stop. for example :randrange(0, 5) yes [0, 1, 2, 3, 4] No, 5
- step: step , The default is 1. for example :range(0, 5) Equivalent to randrange(0, 5, 1)
Returns a number in a random range
Equivalent to choice(range(start, stop, step))
Sample code
import random
random_value = random.random()
print(random_value)
randint_value = random.randint(1, 3) # Returns a random integer
print(randint_value)
uniform_value = random.uniform(1, 3) # Returns a random floating point number
print(uniform_value)
randrange_value = random.randrange(1, 100, 2) # 1 To 100 In steps of 2( We can only get 100 Think of an odd number )
print(randrange_value)
Copy code
The result of each run is different .
A sequence of functions for
random.choice(seq)
Returns a random element from a non empty sequence , If the sequence is empty , Throw an exception
Sample code
import random
value = random.choice(range(1, 100, 2))
# This is equal to random.randrange(1, 100, 2)
print(value)
Copy code
It seems that this method is necessary to shuffle cards
Generate a small case of verification code
import random
# A small case of generating verification number
all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
captcha = ''
for _ in range(4):
a = random.choice(all_chars)
captcha += a # Connection string
print(captcha)
Copy code
random.shuffle()
Method
shuffle(list)
Method randomly sorts all elements of the sequence
Sample code
import random
list1 = ["beautiful" , "cute", "beautiful", 'prefect', "beautiful", " Sweet ", 'lovely']
random.shuffle(list1)
print(list1)
Copy code
random.sample()
Method
random.sample(sequence, k)
, Randomly get a fragment of a specified length from a specified sequence .sample Function does not modify the original sequence . The slice length cannot exceed the original length , Otherwise, an exception will be thrown
Sample code
import random
list1 = ["beautiful", "cute", "beautiful", 'prefect', "beautiful", " Sweet ", 'lovely']
list2 = random.sample(list1, len(list1))
print(" Original list :", list1)
print(" New list :", list2)
Copy code
This method can sort the original sequence without destroying the original sequence
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301649573725.html
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
-
Python string method tutorial - how to use the find() and replace() functions on Python strings
-
Python computer network basics
-
Python crawler series: crawling global airport information
-
Python crawler series: crawling global port information
-
How to calculate unique values using pandas groupby
-
Application of built-in distribution of Monte Carlo simulation SciPy with Python
-
Gradient lifting method and its implementation in Python
-
Pandas: how to group and calculate by index
-
Can you create an empty pandas data frame and fill it in?
-
Python basic exercises teaching! can't? (practice makes perfect)
Random recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module