Common use module-01

Source: Internet
Author: User
Tags month name random shuffle shuffle

Main content:
1. Simple understanding of the module
2. Collections Module
3. Time Module
4. Random Module
5. OS Module
6. SYS module

I. Simple understanding of modules
What is a module. The module is the result of classifying the code that contains the specific functionality. Units written from code
Look at our program, from small to large order: A Code < statement block < code block (function, Class) < module. We are currently writing
All of the PY files are modules.

How to introduce modules?:
1. Import Module
2. from XXX Import module

☆ for modules, you can install and insert a third-party module yourself

Two. Collections module:
Collections module is the main package? Some related operations on collection classes. For example, iterable, iterator and so on. Apart from this, collections also provided? Some data collection classes other than the basic data types
Type. Counter, deque, Orderdict, Defaultdict and Namedtuple
1. Counter
Counter is? a counter. Mainly used to count.
Calculate the number of occurrences of each character in a string of characters:

#calculate the number of occurrences of each character#method One (algorithm):str ='Welcome to view my article.'DiC= {} forCinchStr:dic[c]= Dic.get (c, 0) + 1Print(DIC)#method Two (module):str ='Welcome to view my article.'Print(Counter (str))#the obtained result can be like a dictionary? The same as in the line exercise? [key]
View Code

2. deque bidirectional queue.
※ We need to know two kinds of data structure before we can say bidirectional queue: 1. Stack, 2. Queue

1. Stack: FILO. Advanced after the brick of the walls, the master cook steamed bread
2. Queue column: FIFO. First-come-out, buy fire? Ticket queue, all queued scenes
Because Python does not give the stack module. So we're self-written? A rough version (note that this version has serious concurrency problems)

# 1 barrels of steamed bread. Into the stack # 2. Stack # Properties:   1. List (container) 2. Size (size) 3. Stack top pointer (position of next loaded Element) class Stackfullerror (Exception):    passclass Stackemptyerror ( Exception):    passclass stack:    def __init__ (self, size):        self.index = 0  #  stack top pointer        self.size = size        self.lst = []  # container    def push (self, EL):        if Self.index < self.size:  #  not filled            yet Self.lst.insert (Self.index, el)            Self.index + = 1        else:   # filled with            raise Stackfullerror ("The Stack is full! ")    def pop (self):        if Self.index > 0:            self.index-= 1            return Self.lst[self.index]        else:            raise Stackemptyerror ("The Stack is empty!")

def clear (self):
Self.lst.clear ()
Self.index = 0
def __sizeof__ (self):
Return Len (SELF.LST)
def max (self):
Return self.size
def now:
Return Self.index

# using # 1. Instantiate stack s = Stack (5) s.push ("Bun 1") Print (S.pop ()) s.push ("Steamed bun 2") print (S.pop ()) s.push ("steamed bun 3") print (S.pop ()) S.push (" Steamed Bun 4 ") Print (S.pop ()) s.push (" steamed bun 5 ") Print (S.pop ()) s.push (" Steamed bun 6 ") Print (S.pop ())

  


★ Queue: Python provides a queue module. Make it very convenient to use.

Import Queueq = queue. Queue ()q.put("Li Ka Shing") q.put ("Open") q.put ("Zhang Yi") print (q)print (Q.get ()) print (Q.get ()) print (Q.get ())

Note. If there are no elements in the queue. I can't get any more elements out of it. The program is blocked at this time.


Next, let's take a look at Deque,◇ Note that this queue is in collections.

From collections Import Deque q = deque () Q.append ("Open") # Right Add q.append ("Package Bell")q.appendleft("Zhao Ting") # Left Add Q.appendleft ("Also I High Circle") print (q) print (Q.pop ()) # Right Delete print (Q.popleft ()) # Left Delete

3. Namedtuple named tuples
Named tuples, as the name implies. Name the elements within the tuple. Like what. We say (x, y) This is? a tuple. While. We can also think of this as a point coordinate. At this point, we can use Namedtuple to name the element

From collections Import Namedtuple
Namedtuple ("Point", ["X", "Y"]) p = NT (1, 2) print (p)
Print (p.x) print (P.Y)

4. Orderdict and Defaultdict
Orderdict as the name implies. The dictionary key is unordered by default. and Ordereddict is orderly.

DIC = {' A ': ' Wahaha ', ' B ': ' Fries ', ' C ': ' hu spicy Soup '}print (DIC)
From collections Import ordereddictod = ordereddict({' A ': ' Wahaha ', ' B ': ' Fries ', ' C ': ' Hu Spicy Soup '}) print (OD)

defaultdict: You can set a default value for a dictionary. When key does not exist. Get the default value directly:

From collections Import DEFAULTDICTDD = Defaultdict (list) # Default value Listprint (dd[' Wahaha '])     # [] When key does not exist. The content passed in the row construction method is automatically executed.

  

Three. Time Module (FOCUS)
Time modules are often used when we write programs. For example, how to calculate the time difference. How to show the time according to customer's requirement. Wait a minute.

Importtime print (time.time ()

At this point, we have obtained the system time, but this time .... I can't read it. How to do it. Need to go to the time
Row formatting. So that leads to another? A format of time. In Python, time is divided into three representations:

1. time stamp (timestamp). The timestamp was used from January 01, 1970 00:00 00 seconds to now altogether elapsed how many seconds ... Use float to represent
2. format Time (strftime). This time can be arbitrarily formatted according to our needs.

3. structured Time (struct_time). This time can be divided into the main time classification. Like what. January 01, 1970 00:00 00 seconds This time can be subdivided into years, months, days ..... A whole bunch of stuff.
The time stamp we have seen is time.time (). In general, we do not display such a time to the customer.

Then you need to format the time.

s = time.strftime ("%y-%m-%d%h:%m:%s")  # must remember print (s)

Standard for date formatting:
%y Two-digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m Month (01-12)
One day in%d months (0-31)
%H 24-hour hours (0-23)
%I 12-hour hours (01-12)
%M minutes (00=59)
%s seconds (00-59)
%a Local Simplified Week name
%A Local Full week name
%b a locally simplified month name
%B Local Full month name
%c Local corresponding date representation and time representation
%j Day of the Year (001-366)
%p the equivalent of a local a.m. or p.m.
%u weeks of the year (00-53) Sunday is the beginning of the week
%w Week (0-6), Sunday for the beginning of the week
%W Week of the Year (00-53) Monday is the beginning of the week
%x Local corresponding date representation
%x Local corresponding time representation
%Z the name of the current time zone
Percent% of the number itself


Take a look at the structured time:

print (Time.localtime ()) results: Time.struct_time (tm_year=2017, tm_mon=05, Tm_mday=8, tm_hour=10, tm_min=24,
Tm_sec=42, Tm_wday=0, tm_yday=126, tm_isdst=0)

  


All right. The first thing you see is the current system time, what if you run into time transitions? Like what. Our database is stored in
Had stored such a time: 1888888888. How to display into xxxx year XX month XX day. The transformation of that time must be remembered: the
Some conversions have to be transformed through structured time.

t = time.localtime (1888888888) # structured time  # format this time print (s)

So if I let the user enter a time, how can I convert it into the timestamp of our database store? Or to use structured time :

s = "2020-10-01 12:18:12" T = time.strptime (S, "%y-%m-%d%h:%m:%s") # converted to fabric time print (Time.mktime (t)) # Convert to timestamp

Calculate the time difference:

Import timetrue_time = Time.mktime (Time.strptime (' 2017-09-11 08:30:00 ', '%y-%m-%d%h:%m:%s ')) Time_now = Time.mktime ( Time.strptime (' 2017-09-12 11:00:00 ', '%y-%m-%d%h:%m:%s ')) Dif_time = Time_now-true_timestruct_time = Time.localtime ( Dif_time) print (struct_time) print ('%d '%d '%d '%d '%d ' (struct_time.tm_year-1970,struct_time.tm_mon-1%d)
STRUCT_TIME.TM_MDAY-1,STRUCT_TIME.TM_HOUR,STRUCT_TIME.TM_MIN,STRUCT_TIME.TM_SEC))

  

Four. Random module
All random-related content is in the random module.

Import Randomprint (Random.random ())          # 0-1? Decimal print (random.uniform(3))    # 3-10? decimal
Print (random.randint(1, ten)) # 1-10 integers [1, 10]print (random.randrange(1, 10, 2)) # 1-10 odd [1,10]
Print (random.choice([1, ' Jay Chou ', ["Galen", "hu Spicy Soup"])) # 1 or 2 3 or [4,5]) print (Random.sample ([1, ' 23 ', [4, 5]], 2) # elements Any of 2 combinations
LST = [1, 2, 3, 4, 5, 6, 7, 8]random.shuffle (LST) # random Shuffle Order print (LST)

Five. OS Module
All operating system-related content is in the OS module

os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directoriesos.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on
Os.mkdir (' dirname ') generates a single-level directory, equivalent to the shell mkdir dirnameos.rmdir (' dirname ') delete a single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to the shell rmdir Dirnameos.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints Os.remove () with a column list to delete a file Os.rename ("Oldname", "NewName") Rename File/directory Os.stat (' Path/filename ') gets the file/directory information Os.system ("Bash command") runs the shell command and directly displays Os.popen ("Bash Command"). Read () Run the shell command, get the execution result OS.GETCWD () gets the current working directory, that is, the directory path of the current Python script work os.chdir ("DirName") changes the current script working directory; equivalent to the shell CD
#Os.pathOs.path.abspath (path) returns path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples returnedos.path.dirname (path)Returns the directory of path. is actually the first element of Os.path.split (path)os.path.basename (path)Returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)
Os.path.exists (path) If path exists, returns true if path does not exist, returns Falseos.path.isabs (path) If path is an absolute path, returns Trueos.path.isfile ( Path) returns True if path is a file that exists. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists. Otherwise return Falseos.path.join (path1[, path2[, ...]) will be returned after combining multiple path paths, the parameters before the first absolute path path will be ignored Os.path.getatime (path) Returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) returns the size of the file or directory to which the path was last modified Os.path.getsize (path) returned path
# Special Properties: OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/" OS.LINESEP output the current platform using the line terminator, win "\ r \ n", Linux "\ n" os.pathsep The output string used to split the file path is win under; Linux is: the Os.name output string indicates the current usage platform. Win-> ' NT '; Linux-> ' POSIX '

  


Os.stat () attribute interpretation:

Stat structure:
St_mode:inode Protected Mode st_ino:inode node number. The device that the St_dev:inode resides on. St_nlink:inode number of links. St_uid: The owner's user ID. St_gid: The group ID of the owner. St_size: The size of the normal file in bytes, including data waiting for certain special files. St_atime: Time of last visit. St_mtime: The time of the last modification. St_ctime: "CTime" reported by the operating system. On some systems, such as UNIX, is the time of the most recent metadata change, and on other systems (such as Windows) is the time of creation (see the documentation for the platform for more information).

  


Six. SYS module
All related to the Python interpreter are in the SYS module.

SYS.ARGV command line argument list, the first element is the program itself path Sys.exit (n) exits the program, exit normally exits (0), error exits Sys.exit (1) sys.version get version information for Python interpreter Sys.path Returns the search path for the module, initialized with the value of the PYTHONPATH environment variable Sys.platform returns the operating system platform name

  

Common use module-01

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.