python modules supplement

collections module

  collections module namedtupe method. Also known as a named tuple.

from Collections Import namedtuple 
Point = namedtuple ( ' spatial coordinates ' , ' XYZ ' )     # XYZ can be written in a list form, tuples etc. iterables 
RES = Point (. 3,. 4,. 5 )
 Print (RES)        # spatial coordinates (x = . 3, y =. 4, Z =. 5) 
Print (Point (. 3,. 4,. 5) .x)      # extract x result. 3 
Print (Point (. 3,. 4,. 5) .y)      # extract y result. 4 
Print (Point ( . 3,. 4, 5) .Z)      # extract z 5 results

  Queue queue

# Queue FIFO 
Import Queue 
Q = Queue.Queue () 
q.put ( ' . 1 ' )      # advanced. 1 
q.put ( ' 2 ' )      # intake 2 
q.put ( ' . 3 ' )      # final carry. 3 

Print (q.get ())   # results. 1 
Print (q.get ())    # results 2 
Print (q.get ())    # results 
# NOTE queue using a method, by means of the get function value. When the value is still taken after the value, the program will wait and get the value up until

Double-terminal sequence deque. From the left and right sides can add value to go, but still in accordance with the rules of the queue, FIFO.

from collections import deque
q = deque(['x','y','z'])  
q.append(1)
q.appendleft('a')
print(q)    # deque(['a', 'x', 'y', 'z', 1])
print(q.popleft())  # 结果 a
print(q.pop())  # 1

 

Ordered dictionary OrdereDict.

# Ordered dictionary in which add the key will be added later, this same sort position. 
from Collections Import OrderedDict 
dict_queue = OrderedDict ([(. 1, ' A ' ), (2, ' B ' )]) 

dict_queue [ ' A ' ] =. 1 
dict_queue [ ' B ' ] = 2
 Print (dict_queue)

The default value dictionary defaultdict

from Collections Import a defaultdict 
my_dict = a defaultdict (List)     # Set Default bit listing 
Print (my_dict [ ' A ' ])   # [] 
Print (my_dict)     # results defaultdict (<class 'list'> , { 'a': [ ]})

 

Counting dictionary counter

from collections import Counter
s = 'dadfsfgjhafgbkafha'
s1 = Counter(s)
print(s1)     # 结果 Counter({'a': 4, 'f': 4, 'd': 2, 'g': 2, 'h': 2, 's': 1, 'j': 1, 'b': 1, 'k': 1})

 Time module (time / datatime)

  time module has three forms.

1 stamp. Display now at 0:00:00 on January 1, 1970 from

import time
print(time.time())   # 1563442767.252297

2 Time Format

import time
my_time = time.strftime('%Y-%m-%d %H:%M:%S')
print(my_time)   # 结果 2019-07-18 17:42:09

my_time1 = time.strftime('%Y-%m-%d %X')
print(my_time1)   # 结果 2019-07-18 17:43:38

my_time2 = time.strftime('%Y-%m')
print(my_time2)   # 结果  2019-07

my_time3 = time.strftime('%X')
print(my_time3)   # 结果  17:45:32

3 Structured time

import time
my_time = time.localtime()
print(my_time)  # 结果 time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=17, tm_min=48, tm_sec=22, tm_wday=3, tm_yday=199, tm_isdst=0)

Conversion between the three forms of

'' ' 
Three types of mutual conversion election 
' '' 
# conversion between time and the timestamp structured 
Import Time 
my_1time = the time.time ()     # stamp 
my_3time = time.localtime (my_1time)   # is equivalent to my_3time1 = time.gmtime (my_1time) structured transfer time 
Print (my_3time)   # results time.struct_time (tm_year = 2019, tm_mon = 7, tm_mday = 18, tm_hour = 18, tm_min = 19, tm_sec = 21, tm_wday = 3, tm_yday = 199, the tm_isdst = 0) 
my_1time1 = time.mktime (my_3time)    # structured transfer time stamp 
Print (my_1time1)   # results 1563445161.0 

# structured format time to time into 
my_2time the time.strftime = ( ' %% Y-m -% D ' )    # Format Time 
my_2time1 The time.strftime = ( ' % Y-M-%%% X-D ' , time.localtime (1,563,445,161))   # switch time format 
Print (my_2time1) # Results 2019-07-18 18:19: 21 is 
my_3time the time.strptime = ( ' 2019-07-18 ' , my_2time) # transfected structured time (my_2time formatted to day time, otherwise an error) 
Print (my_3time)

datetime time module

Import datetime 
my_time = datetime.date (2019,6,11)   # custom of time 
Print (my_time)   # results 2019-06-11 
my_time1 datetime.date.today = ()   # current time 
Print (my_time1)   # Results 2019- 07-18 
my_time = datetime.datetime.today ()   # precise time acquiring 
Print (my_time)   # result 2019-07-1818: 59: 00.905379 

# acquisition date 
Print (my_time.year)     # results 2019 
Print (my_time. month The)    # results. 7 
Print (my_time.day)      # results 18
Print (my_time.weekday ())    # result. 3 
Print (my_time.isoweekday ())   # results. 4 

# datetime arithmetic operation 
Import datetime 
now_day = datetime.date.today ()    # date object 
last_day = datetime.timedelta (days = 7)   # TIMEDATE on which the objects 

REC = now_day + LAST_DAY    # date + timelate target objects 
Print (REC)    # date objects: results 2019-07-25 
RECl = REC - now_day   # date object - the object date 
Print (RECl)   # TIMEDATE on which the result of the object 7 days, 0:00:00

 Random random module

# Random number acquired 
Import Random
 Print (random.random ())    # Get the number of results between 0. 1: 0.21267928084158305 
Print (random.uniform (. 1, 10))   # Get the number of results between 1 and 10: 6.744952496036854 
Print (the random.randint (1, 10))   # obtain 1 (including 1) between the integer result to 10 (including 10):. 3 
Print (the random.choice ( ' 123 ' ))   # Gets a string element. (Iterables) Results:. 3 
Print (random.sample ([. 1, ' 23 is ' ,. 3, [4,5]], 2)) # acquired two string elements. (Iterables) Results: [ '23', [4, 5]]

sys module

  sys python interpreter module and tightening of the associated

sys.argv command line parameters List, the first element of the program itself is the path 
sys.exit (n) to exit the program, when the normal exit exit (0), exit the error sys.exit ( 1 ) 
sys.version get the version of Python interpreter information 
sys.path return module search path, use the PYTHONPATH environment variable initialization value 
sys.platform returns the name of the operating system platform

os module

  os module related to the operating system

os.makdirs ( ' dirname1 / dirname2 ' ) may generate a multilayer recursive directory 
os.removedirs ( ' dirname1 ' ) if the directory is empty, delete, and recursively to the parent directory, should be empty, delete, and so analogy 
os.mkdir ( ' dirname ' ) to generate a single level directory; it is equivalent to the shell dirname mkdir 
os.rmdir ( ' dirname ' ) empty directory delete a single stage, if the directory is not empty can not be deleted, being given; corresponds to the shell rmdir dirname 
os.listdir ( ' dirname ' ) lists all the files and subdirectories in the specified directory, including hidden files, and print in a list 
os.remove () to delete a file 
os.rename ( " oldname " , " newname " ) weight name the file / directory 
os.State ( 'path / filename ' ) get the file / directory information 

os.system ( " bash the Command " ) to run shell commands, displayed directly 
os.popen ( " bash the Command) .read () run shell commands to get the results 
os.getcwd () Gets the current working directory that the current directory path python script work 
os.chdir ( " dirname " ) script to change the current working directory; under the equivalent cd shell 

os.path 
os.path.abspath (path) returns the absolute path to the path of standardized 
os. path.split (path) into the path directory and file name tuple returned 
os.path.dirname (path) returns the directory path of the fact that the first element os.path.split (path) of 
os.path. basename (path) returns the last path of the file name. how path to / \ or end, it will return a null value. That os.path.split (path) of the second element 
os.path.exists (path) if the path exist, return True; if the path does not exist, returns False 
os.path.isabs (path) if the path is the absolute path, returns True
os.path.isfile (path) if the path is a file exists, returns True. Otherwise it returns False 
os.path.isdir (path) if the path is a directory exists, then return True. Otherwise it returns False 
os.path.join (path1 [, path2 [, ...]]) will return after a combination of multiple paths parameters before the first absolute path will be ignored 
os.path.getatime (path) return path points to the last access time of a file or directory 
os.path.getmtime (path) returns the file or directory path points to the last modification time 
os.path.getsize (path) return path size
os module operation

Serialization

 Sequence refers to a string, a sequence of data types is converted into a string of other processes. Deserialize string is transformed into other data processes. There are two series of modules, json module and pickle module. Both a little different, json support for multiple programming languages, a wide range, but less support for data types. python pickle module supports all data types, but does not support other programming languages.

Serialization and deserialization json There are four ways.

dumps and loads 
the dump and Load 
'' ' 

Import JSON 
str1 =' ABCDEFG ' 
dict1 = {} 
for K, V in the enumerate (str1,. 1): 
    dict1 [V] = K 
str_dict = json.dumps (dict1) 
Print (str_dict, type (str_dict)) 
yuan_dict = json.loads (str_dict) 
Print (yuan_dict, type (yuan_dict)) 

F = Open ( 'json_file', 'W') 
DIC = { 'K1': 'V1', 'K2': ' V2 ',' K3 ':' V3 '} 
the json.dump (DIC, F) #dump method of receiving a file handle, which directly converts into a dictionary json string to the file 
f.close () 

F = Open (' json_file ' ) 
DIC2 the json.load = (F) #load method of receiving a file handle, which directly converts the file into a data structure returned json string 
f.close () 
Print (type (DIC2), DIC2)
View Code

 

Guess you like

Origin www.cnblogs.com/huaiXin/p/11208668.html