Python Learning day20 Common modules Section

Source: Internet
Author: User

Module:
Pip Install module name
Mounting module
Import module from collections import Namedtuple
Collections module:
Several additional data types are available:
Counter, Deque, Defaultdict, namedtuple\ordereddict
1.namedtuple: Generate a tuple that can access the content of an element by using a name
2.deque: Double-ended queue to quickly append and eject objects from the other side
3.Counter: Counter
4.OrderedDict Dictionary Ordering
5,defaultdict Dictionary resolution method

Namedtuple can be named Ganso:
for a named meta-patriarch, it can be accessed by name.
namedtuple (' point ', [' X ', ' y '])
p=p (+)
print (p.x)
print (p.y)
Practicality: make it easier for others to see the code
Deque module   Double-ended queue:
queue: FIFO
Both values are first taken out, and values are taken from both ends. There are appendleft and Popleft
Ordereddict dictionaries in order:
from collections import ordereddict
Direct strong to Dictionary when Dict is converted to orderedict
Defaultdict Dictionary Resolution:
from collections import defaultdict
values=[11,22,33,44,55,66,77,88,99]
my_dict=defaultdict (list)
print (my_dict)
print (my_ Dict.get (' K '))
my_dict[' K '].append (1)
print (my_dict)
Save a step to create a key value
Counter calculates the number of occurrences in each character dictionary:
Same as Import module method
Use a dictionary method to sort the number of occurrences of a string of letters


Time module:
Direct Import Time
Time.time () timestamp
Represents time three ways:
(1) timestamp, from January 1, 1970 0 o'clock, the offset by the second, float type. Identify time
and use that time to calculate the time.
(2) formatted time string (format string): ' 1999-12-06 '
(3) Yuan zu time ()


Time.strftime (') is followed by a formatted format
%y is the year%M is the month%d is the day, except the year is the lowercase%h:%m:%s when every minute capitals
The Big%i is a 12-hour%p that was last afternoon
%a is simplified for the day of the week name capitalization is not simplified
%c local corresponding Standard time
%j Day of the year
%x Date
%x time
Time.localtime () default parameter The current time is also enclosed in parentheses Time.time
Time.struct_time () do time to calculate structured time
Time.gmtime () is UTC London time after which you can add time stamp to the digital time
Timestamp-to-structure ↑

Time.mktime () structured turn timestamp
Structured time-to-string time:
Time.strftime () to be converted before parentheses, followed by the format
Time conversion of a string to structured time
Time.strptime () in front of the written time, after the parentheses are given what format

Structured time turn%a%b%d%h:%m:%s%y string
Time.asctime () can be time.localtime ()
Convert structured time to fixed format
String turn into structured time
Time.ctime () Give a time stamp to
Time Progenitor:
Do the time calculation
Random module:
Random.random () randomly generates decimals greater than 0 and less than 1
Random.uniform (1,3) randomly generates decimals greater than 1 and less than 3
Random.randint (1,5) randomly generates integers greater than or equal to 1 and less than or equal to 5
Random.randrange (1,10,2) an odd number greater than or equal to 1 and less than 10

Random.choice ([1, ' 23 ', [4,5]]) list randomly returns one, parameter is an iterative object
Random.sample ([1, ' 23 ', [4,5]],2) any of two combinations
Shuffle Order:
item=[1,2,3,4]
Random.shuffle (item)
Print (item)
Random Verification Code:
1.
ret=random.sample (range), 6
print (". Join" ((str (i) for i in RET ))
2.
num_lst=[]
For I in range (6):
num=random.randint (0,9)
num_lst.append (num)
print (". Join (NUM_LST)))
English
def func (n):
ret= "
For i in range (n):
num = random.randint (0,9)
ALPHA = Chr (Random.randint (65,90))
ALPHA=CHR (Random.randint (97,122))
Value=random.choice ([str (num), Alpha,alpha])
ret +=value
return ret
Print (func (6))
SYS module:
Connected to the Python interpreter:
The relative path to the sys.argv file. Can be used to write login
Import Sys
If sys.argv[1] = = ' Alex ' and if sys.argv[2]== ' 123 '
Print (' Login successful ')
Else
Print (' Login failed ')
Sys.version Print is a Python version that can be used to determine if the versions are supported
Use StartsWith to judge if the opening is not supported Sys.exit () exit
Sys.path from the back to see Module import path
can be behind Sys.path. Append add the file path in
Sys.platform return operating system platform to determine the operating system platform to replace the path
OS module:
An OS module is an interface that interacts with the operating system
1. Directory-related
2. Path-related
3. FILE-related
4. Operating system-related
5. Related to executing system commands
One floor with mkdir
Multilayer with Makedirs
Os.listdir (OS.GETCWD ())
Get the content into a list.
Os.stat (' path/filename ') Get File status stat structure
OS.SEP Path Stitching
OS.LINESEP output The line terminator used by the current platform
OS.PATHSEP output string for splitting the file path
Os.name View Current operating system
Os.system (' dir ') look at all the files in the current directory somewhat like exec execution commands with this
Os.popen is kind of like eval, you can use this if you want to get information.
Os.path
Os.path.abspath (path) returns the absolute path normalized by path
is actually the first element of Os.path.split (path)
Os.path.dirname (path) returns the path directory basename returns the last file directory
Os.path.join can splice the path by itself according to the operating system stitching
Serialization Module
The process of converting an original dictionary, list, and other content into a string is called serialization.
Only strings can be stored in the file
converting data types in programs to STR
Application:
1. Save File
2. Network Transmission
Purpose of serialization
1. Persisting custom objects in some form of storage
2. Passing objects from one place to another
3. Make the program more maintainable
Data structure to STR is serialized
The inverse of the turn is deserialization
JSON module
Dumps is the serialization process
Loads is the process of deserialization
Import JSON
d={' k ': ' V ', ' K2 ': [1,2,3,4]}
Sd=json.dumps (d)
Print (Sd,type (SD))
j=json.loads (SD)
Print (J,type (j))
Dump can be passed into the file
Load can take the conversion from the file
Ensure_ascii=false is used when the file is saved
Two methods:
1. Serializing Dump Dumps
2. Deserialization of the load loads
JSON is generally used only for processing dictionary list meta-ancestors
Pickle modules can be used when you define some data types

Pickle can serialize a number of custom data type games
JSON is a data type common to all programming languages network programming more

shelve module Python-provided serialization tool
Import shelve
f = shelve.open (' Shelve_file ')
f[' key ']={' int ': 10} can have multiple keys
F.close ()

Import shelve
F1 = Shelve.open (' Shelve_file ')
existing=f1[' key ']
F1.close ()
This module is limited and does not allow multiple applications to write to the same db at the same time.
Set Writeback=true to modify key, otherwise key exists cannot be modified

Python Learning day20 Common modules Section

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.