current position:Home>With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~
With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~
2021-08-23 09:35:53 【It's dream】
️「Python」 Advanced , Catch all the high-level grammar ! Don't look at regret series ~
Hello, Hello, my name is Dream ah , An interesting Python Blogger , A little white , Please go easy on me
CSDN Python New star creators in the field , Author Zhou Bang NO.24 , Sophomore reading
Introductory notes : This paradise never lacks genius , Hard work is your final ticket !
Last , May we all shine where we can't see , Let's make progress together
“ Ten thousand times sad , There will still be Dream, I've been waiting for you in the warmest place ”, It's me ! Ha ha ha ~
「Python」 Advanced ️:
Advanced functions
1. Time function
stay Python in , There are usually several ways to express time :
(1) Time stamp ;
(2) Formatted time string ;
(3) time tuples (struct_time).
1. Generally speaking , Time stamp
It means from 1970 year 1 month 1 Japan 00:00:00 Start offset in seconds .
import time; # introduce time modular
ticks = time.time()
print(" The current timestamp is :", ticks)
2. We can use time Modular strftime The method is to Format date
.
import time
# Format as 2016-03-20 11:45:39 form
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
3. return struct_time
The main functions of are gmtime()、localtime() and strptime(),struct_time Tuples .
2. Calendar function
1.calendar.calendar(year,w=2,l=1,c=6)
Returns the year Annual calendar ,3 Month and row , The interval is c. The daily width interval is w character . The length of each line is 21* W+18+2* C.l Is the number of lines per week .
import calendar
print(calendar. firstweekday())
print(calendar.isleap(2018))
print(calendar.calendar(2021,w=1,l=1,c=6))
Then we can get our date table , Is it very nice:
2. Returns the setting of the start date of the current week . By default , First load caendar Module returns 0, Monday .
calendar. firstweekday()
3. If it's a leap year, return True, Otherwise false.
calendar.isleap(year)
4. Back in the Y1,Y2 The total number of leap years between two years .
calendar.leapdays(y1,y2)
5. Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .
print(calendar.month(2021,2,w=2,l=1))
6. Returns a single nested list of integers . Each sublist load represents an integer for a week .Year year month All dates outside the month are set to 0; The days in the range are indicated by the day of the month , from 1 Start .
calendar.monthcalendar(year,month)
7. Returns two integers . The first is the date code of the day of the week of the month , The second is the date code of the month . Day from 0( Monday ) To 6( Sunday ); Month from 1 To 12.
calendar.monthrange(year,month)
8.calendar.prcal(year,w=2,l=1,c=6)
amount to print(calendar.calendar(year,w,l,c))
3. Random number function
1.random.random()
Used to generate a 0 To 1 The number of random characters of : 0 <= n < 1.0.
import random# Generate the first random number
print("random():", random.random())# Generate the second random number
print("random():", random.random())
2.random.uniform(a,b)
return a,b Between random floating-point numbers , Range [a,b] or [a,b] It depends on To the nearest ,a Not necessarily better than b Small .
3.random.randint(a,b)
return a,b Integer between , Range [a,b], Be careful : The passed in parameter must be an integer ,a Be sure to than b Small .
4.random.randrang([start], stop[, step])
Returns an integer with an interval , You can set step. Only integers can be passed in ,random.randrange(10, 100, 2),
The result is equivalent to from [10, 12, 14, 16, … 96, 98] Get a random number in the sequence .
5.random.choice(sequence)
from sequence( Sequence , It's an ordered type ) Get an element at random , list 、 Tuples 、 All strings belong to sequence.
random.randrange(10,100,2)
# The result is equivalent to
random.choice(range(10,100,2)
6.random.shuffle(x[,random])
Used to disorganize the elements in the list , Commonly known as shuffle .
p = ["Python","is", "powerful","simple”]
random.shuffle(p)
7.random.sample(sequence,k)
Get... Randomly from a specified sequence k Elements returned as a fragment ,
sample Function does not modify the original sequence
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice = random.sample(list, 5)
print(slice)
print(list)
Closure and Decorator
1. Closure :
Python Functions support nesting . If you scope an external function in an internal function ( Non global scope ) The variables are quoted , Then the inner function will be called closure . Closure
Need to satisfy the following 3 Conditions :
- Exists in two nested functions , And closures are internal functions ;
- The inner function references the variables of the outer function ( Free variable );
- The external function will return the function name of the internal function .
def outer(start=0):
count=[start]
def inner():
count[0]+=1
return count[0]
return inner
out = outer(5)
print(out())
2. Decorator :
Suppose we have developed an existing function , Subsequent may increase temporary demand , For example, insert logs , We can add a wrapping function , It is responsible for these additional requirements , This wrapping function is Decorator
.
Decorators are mainly used in the following scenarios :
- Introducing logs ;
- Function execution time statistics ;
- Prepare for function execution ;
- Clean up after function execution ;
- Permission to check ;
- cache .
Decorator is a function , It needs to receive a parameter , This parameter represents the modified function . for example , There is one of the following Decorator function
:
def myDectoration(func):
def inner():
print(" Executing internal function ")
func()
return inner
def printMessage():
print("-------- Welcome -------")
pm = myDectoration(printMessage)
pm()
The decorator is a nested function, and the inner function is a closure .
The external function receives the modified function (func)
By adding... Before the function definition @ Symbol and decorator name , Implement the wrapper of the decorator to the function . to f1 Function plus decorator , Examples are as follows :
@w1
def f1():
print(’f1')
here , The program will automatically compile and generate the code that calls the decorator function , Equivalent to :
f1 = w1(f1)
Multiple decorators :
Multiple decorators are applied to a function , The call order is from bottom to top .
common Python Built in functions
1.map function
map The function calls... With each element in the parameter sequence function function , Save the result returned after each call as an object
func = lambda x:x+2
result = map(func, [1,2,3,4,5])
print(list(result))
flow chart :
2.filter function
filter The filter function performs a filter operation on the specified sequence .
filter The function is defined as follows :
filter(function,iterable)
The first 1 An argument can be the name of the function ; The first 2 The first parameter represents the sequence 、 A container or iterator that supports iteration .
func = lambda x:x%2
result = filter(func, [1, 2, 3, 4, 5])
print(list(result))
flow chart :
File operations
1. Opening and closing of files
stay python in , Use open Method to open a file :
open( file name , Access pattern )
- “ file name ” Must fill in
- “ Access pattern ” It's optional
Access pattern :
All open files , Remember to use close Method to close the file :
# Create a new file , The file named :test.txt
f = open(itheima.txt', 'w')
# Close this file
f.close()
2. Reading and writing of documents
Writing documents :
Write data to file , Need to use write Method to accomplish , When operating on a file , Every call write Method , The written data will be appended to the end of the file :
f = open('itheima.txt', 'w')
f.write(‘hello itheima, i am here!’)
f.close()
Reading documents :
The way 1: Use read Method to read the file
f = open('itheima.txt', 'r')
content = f.read(12)
print(content)
print("-"*30)
content = f.read()
print(content)
f.close()
The way 2: Use readlines Method to read the file
f= open('itheima.txt', 'r')
content = f.readlines()
i = 1
for temp in content:
print("%d:%s" % (i, temp))
i += 1
f.close()
The way 3: Use readline Method reads data line by line
f = open('itheima.txt', 'r')
content = f.readline()
print("1:%s"%content)
content = f.readline()
print("2:%s"%content)
f.close()
File location reading and writing :
f = open("itheima.txt", "r")
str = f.read(4)
print(“ The data read is : ”, str)
position = f.tell()
print(" Current file location : ", position)
3. Renaming and deleting files
os Module rename() Method to rename the file . The format is as follows :
os.rename( File name to be modified , New file name )
os Module remove() Method to delete a file . The format is as follows :
os.remove( File name to be deleted )
4. File related operations
1. Create folder
os Modular mkdir Method to create a folder , Examples are as follows :
import os
os.mkdir(" Zhang San ")
2. Get current directory
os Modular getcwd Method to get the current directory , Examples are as follows :
import os
os.getcwd()
3. Change the default directory
os Modular chdir Method to change the default directory , Examples are as follows :
import os
os.chdir("../”)
4. Get directory list
os Modular listdir Method to get a list of directories , Examples are as follows :
import os
os.listdir (”./”)
5. Delete folder
os Modular rmdir Method to delete a folder , Examples are as follows :
import os
os.rmdir (” Zhang San ”)
The last little benefit to everyone : If you want to get started quickly python My friends , This is sorted out in detail PPT Can quickly help everyone to fight python Basics , You can download it if you need it Python A complete set of introductory basic tutorials + Xiaobai Express + You won't come to me !
All right. , That's all I want to share with you today
️️️ If you like , Don't be stingy with your one key triple connection ~
Voting session :
copyright notice
author[It's dream],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823093548234a.html
The sidebar is recommended
- [Python introduction project] use Python to generate QR code
- Compile D + +, and use d to call C from python
- Quickly build Django blog based on function calculation
- Python collects and monitors system data -- psutil
- Finally, this Python import guide has been sorted out. Look!
- Quickly build Django blog based on function calculation
- Python interface test unittest usage details
- Implementation of top-level design pattern in Python
- You can easily get started with Excel. Python data analysis package pandas (VII): breakdown
- Python simulation random coin toss (non optimized version)
guess what you like
-
Python tiktok 5000+ V, and found that everyone love this video.
-
Using linear systems in python with scipy.linalg
-
Using linear systems in python with scipy.linalg
-
Together with Python to do a license plate automatic recognition system, fun and practical!
-
You can easily get started with Excel. Python data analysis package pandas (XI): segment matching
-
Advanced practical case: Javascript confusion of Python anti crawling
-
Using linear systems in python with scipy.linalg
-
Fast power modulus Python implementation of large numbers
-
Quickly build Django blog based on function calculation
-
This paper clarifies the chaotic switching operation and elegant derivation of Python
Random recommended
- You can easily get started with Excel pandas (I): filtering function
- You can easily get started with Excel. Python data analysis package pandas (II): advanced filtering (I)
- You can easily get started with Excel. Python data analysis package pandas (2): advanced filtering (2)
- You can easily get started with Excel. Python data analysis package pandas (3): making score bar
- Test Development: self study Dubbo + Python experience summary and sharing
- You can easily get started with Excel. Python data analysis package pandas (V): duplicate value processing
- How does Python correctly call jar package encryption to get the encrypted value?
- Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same
- Python simple Snake game (single player mode)
- Using linear systems in python with scipy.linalg
- Python executes functions and even code through strings! Come and understand the operation of such a top!
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- [Python introduction project] use Python to generate QR code
- Vanessa basks in her photos and gets caught up in the golden python. There are highlights in the accompanying text. She can't forget Kobe after all
- [windows] Python installation pyteseract
- [introduction to Python project] create bar chart animation in Python
- Fundamentals of Python I
- Python series tutorials 116
- Python code reading (chapter 35): fully (deeply) expand nested lists
- Practical series 1 ️⃣ Wechat applet automatic testing practice (with Python source code)
- Python Basics: do you know how to use lists?
- Solution of no Python 3.9 installation was detected when uninstalling Python
- [Python homework] coupling network information dissemination
- [common links of Python & Python]
- Python application software development tool - tkinterdesigner v1.0 5.1 release!
- [Python development tool tkinterdiesigner]: example: develop stock monitoring alarm using Tkinter desinger
- [Python development tool Tkinter designer]: Lecture 2: introduction to Tkinter designer's example project
- [Python development tool Tkinter designer]: Lecture 1: introduction to the basic functions of Tkinter Designer
- [introduction to Python tutorial] use Python 3 to teach you how to extract any HTML main content
- Python socket implements UDP server and client
- Python socket implements TCP server and client
- leetcode 1261. Find Elements in a Contaminated Binary Tree(python)
- [algorithm learning] 1486 Array XOR operation (Java / C / C + + / Python / go / trust)
- leetcode 1974. Minimum Time to Type Word Using Special Typewriter(python)
- The mobile phone uses Python to operate picture files
- [learning notes] Python exception handling try except...
- Two methods of using pandas to read poorly structured excel. You're welcome to take them away
- Python sum (): the summation method of Python
- Practical experience sharing: use pyo3 to build your Python module
- Using Python to realize multitasking process