Common Module Two
================= Collections Module ==================
========= namedtuple can be named by a tuple ============ fromCollectionsImportNamedtuplepoint=namedtuple (' point ', [' X ', ' y ']) P=point (ON)circle=namedtuple (' Circle ', [' X ', ' y ', ' r ']) c=circle (1,2,1)print (p.x)print (P.Y)print (c.x)print (C.Y)print (C.R)======== Queue FIFO-bidirectional queue deque============processing tasks-dealing with one less fromCollectionsImportdeque#q=deque ([+]) #Q.append (4)#Q.Appendleft (5) #Q.pop ()#Q.popleft () #print (q) # deque ([1, 2, 3])#Q.extendleft ([up]) # no entend======== ordered dictionary ordereddict============ fromCollectionsImportordereddict#dic=dict (' A ', 2), (' B ', 3), (' C ', 6)])#print (DIC) # {' A ': 2, ' B ': 3, ' C ': 6}#dic=ordereddict (' A ', 2), (' B ', 3), (' C ', 6)])#print (DIC) # ordereddict ([' A ', 2), (' B ', 3), (' C ', 6)])#======== has a default worth dictionary defaultdict============#From collections Import Defaultdict##dic=defaultdict (list) # inside must be a function function that can be called #dic[' K '].append (123)#print (DIC)#dic=defaultdict (lambda: ' N/a ') # parentheses are a default value###======== counter Returns a count dictionary ============
=================
Time () module
==================
1 Timestamp-----1970 1 1----Identify the only time used to calculate the 2 string time-----time.strftime ('%y-%m-%d%h:%m:%s ', the default is Time.localtime ()) 3 Format Time-----time.localtime () time.gtime ()#Import Time#t1=time.time () #============= timestamp ======= Calculator application ============##t2=time.localtime () # Time in the east side of the GMT #=========== structured time ========= operation ========#t3=time.gmtime () # Standard Time 8 hours late #=========== structured time ========= operation ========###t=time.mktime(Time.localtime (Time.time ())) # Structured--->> timestamps#t=time.strftime('%y-%m-%d ', Time.localtime ()) #结构化时间--->> string time #========== string Time ======= show People ===== ===#tt=time.strptime(' 2018-08-23 ', '%y-%m-%d ') # string time-->> structured time #========== string Time ======= show People ========= ##t4=time.ctime(Time.time ())#t5=time.asctime(Time.localtime ())##Time . Sleep (0.1) # = = =I/o blocking does not consume CPU #Print (t2.tm_year,t2.tm_mon,t2.tm_mday,t2.tm_hour,t2.tm_min,t2.tm_sec,sep= ': ')
Example 1 calculates the time after a few days#time_str= ' 2015-09-23 '#def add_days (my_time,num):#temp_time=time.strptime (my_time, '%y-%m-%d ')#temp_time=time.mktime (temp_time)#Actual_time=temp_time+3*24*3600*num#new_time=time.localtime (actual_time)#new_time=time.strftime ('%y-%m-%d ', new_time)#return New_time#Print (Add_days (time_str,5))
Example 2 See how long a time has elapsed #Import Time#old_time_str1= ' 2015-09-10 08:30:00 '#struct_time=time.strptime (old_time_str1, '%y-%m-%d%h:%m:%s ')#true_time=time.mktime (struct_time)#time_now=time.time ()#dif_time=time_now-true_time-8*3600#struct_time=time.localtime (dif_time)#print ('%d '%d '%d '%d '%d '% (struct_time.tm_year-1970,struct_time.tm_mon-1,struct_time.tm_mday-1, STRUCT_TIME.TM_HOUR,STRUCT_TIME.TM_MIN,STRUCT_TIME.TM_SEC))#str_time=time.strftime ('%d%H%M%s ', struct_time)#print (str_time)
=========================
Random number () module
==========================
#print (random. Random ()) # (0,1) float #print (random. Randint (1,5)# [1,5] int #print (random. Uniform (1,5)# [1,5] float #print (random. Randrange (1,5)) # [1,5] int #print (random. Choice (' ABCD ')) # An iterative object randomly selects a #print (random. Sample (' ABCD ', 3)# Iteration object randomly selects multiple return values as List #li=[1,2,3,4]#Random. Shuffle (li) # randomly changing the order of data structures that can be indexed
example verification code # import random # check= " # for I in range (8): # M=CHR (Random.choice (Range (ord (' A '), Ord (' Z '))) # N=CHR (Random.choice (Range (ord (' A '), Ord (' Z ')))) # O=random.randint (0,9) # String=random.choice ([m,n,o]) # Check+=str (string) # print (check)
================
Serialization module
================
The process of converting an original dictionary, list, and other content into a string is called = = = serialization Save FileNetwork Transmission
The purpose of =========== serialization =========== to persist custom objects in some form of storage Transfer objects from one place to another the program is more maintainable ===json==provides four functions dumps dump load loads dumps loads network transfer processing string #Import JSON#d={' k ': ' V ', ' K2 ': [All-in-all]}#Print (D,type (d)) #{' K ': ' V ', ' K2 ': [1, 2, 3]} <class ' Dict ' >##Sd=json.dumps (d)#Print (Sd,type (SD)) # serialization {"K": "V", "K2": [1, 2, 3]} <class ' str ' >###s= ' {"K": "V", "K2": [[i]} '##D=json.loads (s) # deserialization#Print (D,type (d)) # {' K ': ' V ', ' K2 ': [1, 2, 3]} <class ' Dict ' ># Load Dump file operation data persisted one- timeImportJsond={'k':'v','K2': [A]}f=open ('Json_file','W') json.dump (D,f,ensure_ascii=true)#F.close () F=open ('Json_file') ret=json.load (f) f.close ()Print(ret)Print('China'. Encode ('GBK'))#b ' \xd6\xd0\xb9\xfa 'Print(ASCII ('China'))#' \U4E2D\U56FD ' Unicode ===pickle===
# JSON (only basic data types such as dictionary list tuples) are used to convert between strings and Python data types # All programming Languages Universal # pickle=== serialization for custom data types (game character data) # only Python can use # # sequence To customize some of the data types
===shelve===a simple data type---used to modify#Import Shelve##f=shelve.open (' Shelve_file ', writeback=true) #{' int ': 5, ' str ': ' A '}## f=shelve.open (' shelve_file ') #{' int ': 1, ' str ': ' A '}#f[' key ']={' int ': 1, ' str ': ' A '}#f[' key ' [' int ']=5#f.close ()#
#f1=shelve.open (' Shelve_file ') # Memory consumption#ret=f1[' key ']#f1.close ()#print (ret)
Common Module Two---time--random--collections--json--pickle--shelve