Module II; tuple named time, a random number, os, sys


      
Today, content 
collection module
time and the datetime module
os module
sys module
module random
sequencing module
JSON
the pickle
The subprocess module (subprocess)


1, collection module
1 ", named tuple **** namedtuple
2" **** queue Queue
. 3 "deque the deque
. 4" ordered dictionary a defaultdict

. 1, named tuple
from Collections Import namedtuple
Point = namedtuple ( 'coordinates', [ 'x', ' y', 'z']) # the second parameter either can be transferred iterables
point = namedtuple ( 'coordinates', 'xy z') # string may be passed between the string separated by a space but
p = point (1,2,5) # must be noted that the number of elements with the number of values namedtuple second argument inside the same
print (p) # coordinates (X =. 1, Y = 2, Z =. 5)
Print (PX) #. 1
Print (Py) # 2
Print (PZ) #. 5
Case Column 2:
City1 = namedtuple ( 'Japanese', ' Person size name ')
# = namedtuple City (' Japan ', [' name ',' Person ',' HHJ '])
the City2 = namedtuple (' poker ', [' color ',' number ',' ba '] )
c = city1 ( 'tokyo', 'guitar teacher', 'er') # Japan (name = 'tokyo', person = 'guitar teacher' size = 'ER')
Print (c)
c2 = the City2 ( 'tokyo '' guitar teacher ',' er ')
Print (c2) # playing cards (color = 'Tokyo', number = 'guitar teacher', BA = 'ER')

2, queue: FIFO (First in the FIFO First OUT)
Import Queue
q = queue.Queue () # generates queue object
q.put ( 'first') # value added to the queue
q.put ( 'SECOND')
q.put ( 'THIRD')
Print (q.get ()) # value from the queue
Print (q.get ())
Print (q.get ())
Print (q.get ()) # If the value is taken over in the queue will wait until get the value from the queue stopped in situ

3, the deque deque
PS: queue does not support arbitrary position interpolation should
only end-interpolated (can not jump the queue)
# specific points: deque may interpolation index at any position
from the deque Collections Import

Q = the deque ([ 'A' , [ 'B'], [ 'C']])
Print (q.append (. 1)) ### None
Print (q.pop ()). 1 #
print (q) #deque ([ 'clam shell sea J', 2, 'A', [ 'B'], [ 'C']])
Print (q.popleft ()) # sea clamshell J
Print (Q .popleft ()) # 2
. 4, ordered dictionary: how is how to create a sequence of (about creation order)
from Collections Import OrderedDict
Old = OrderedDict ()
Old [ '. 1'] = '111' first key of
Old [ 'Y'] = 'EE'
Old [ 'Z'] = '333'
Print (Old)
for I in Old:
Print (I)
. 5, counter counts (present in the form of key-value pairs)
from Collections Import counter
S = 'abcdeabcdabcaba'
res = Counter(s)
Print (RES) #Counter ({ 'A':. 5, 'B':. 4, 'C':. 3, 'D': 2, 'E': 1})
2, time module:
three forms
1. ***** stamp
2. time formatter (used to display the posters)
3. structured time
ps: not straightforward timestamp formatting time, must be converted to a structured time, and then converted into a format time of
1, time stamp Import
print (the time.time ()) # seconds stamp
print (time.strftime ( '% Y-% m-% d% X')) # date, hour, minute
print ( the time.sleep (. 1))
Print (The time.strftime ( '% Y-M-% D%% H:% M:% S')) # date, hour, minute
print (time.strftime ( '% H: % m ')) # division
print (time.strftime ('% Y / % m ')) Years #
3, the structure of the time
print(time.localtime())
print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
import datetime
print(datetime.date.today()) # date>>>:年月日
print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
Print (res.month)
Print (res.day)
Print (res.weekday ()) # 0 for 0-6 day of the week Monday
print (res.isoweekday ()) # 1-7 7 is the day of the week on Sunday
(** ****)
date date Object target = +/- timedelta objects
timedelta target = +/- date object date object
current_time = datetime.date.today () # date object
timetel_t = datetime.timedelta (days = 7) # timedelta objects
res1 = current_time + timetel_t # date objects

Print (CURRENT_TIME - timetel_t)
Print (RES1-CURRENT_TIME)
# UTC time (gap 8 hours)
dt_today datetime.datetime.today = ()
= datetime.datetime.now dt_now ()
dt_utcnow = datetime.datetime.utcnow ()
Print (dt_utcnow, dt_now, dt_today)
. 3 # module random *****
Import Random

Print (the random.randint (1,6)) # Random a number range of integers take your provided comprising end-
print (random.random ()) # randomly decimal between 0-1
Print (the random.choice ([1,2,3,4,5,6])) # Yaohao randomly an element from the list
RES = [1,2,3,4,5,6]
random.shuffle (RES) # shuffling
print (res)
case:
uppercase letter lowercase alphanumeric
random digit verification 5 code
CHR
random.choice
Encapsulated into a function, the user would like to generate several generates several

DEF GET_CODE (n-):
# random string is empty
code = ''
for I in Range (n-): 5 cycles #
Mr # lowercase to uppercase random alphanumeric
upper_str = CHR (the random.randint (65, 90))
lower_str = CHR (the random.randint (97, 122))
random_int = STR (the random.randint (0,. 9))
# choose one of the above three randomly a random codes of a bit
code the random.choice + = ([upper_str, lower_str, random_int])
return code returned randomly drawn numbers #

RES GET_CODE = (. 5)
Print (RES) # 5 obtained random character a string
4, os module: module dealing with the operating system
      
Today, content 
collection module
time and the datetime module
os module
sys module
module random
sequencing module
JSON
the pickle
The subprocess module (subprocess)


1, collection module
1 ", named tuple **** namedtuple
2" **** queue Queue
. 3 "deque the deque
. 4" ordered dictionary a defaultdict

. 1, named tuple
from Collections Import namedtuple
Point = namedtuple ( 'coordinates', [ 'x', ' y', 'z']) # the second parameter either can be transferred iterables
point = namedtuple ( 'coordinates', 'xy z') # string may be passed between the string separated by a space but
p = point (1,2,5) # must be noted that the number of elements with the number of values namedtuple second argument inside the same
print (p) # coordinates (X =. 1, Y = 2, Z =. 5)
Print (PX) #. 1
Print (Py) # 2
Print (PZ) #. 5
Case Column 2:
City1 = namedtuple ( 'Japanese', ' Person size name ')
# = namedtuple City (' Japan ', [' name ',' Person ',' HHJ '])
the City2 = namedtuple (' poker ', [' color ',' number ',' ba '] )
c = city1 ( 'tokyo', 'guitar teacher', 'er') # Japan (name = 'tokyo', person = 'guitar teacher' size = 'ER')
Print (c)
c2 = the City2 ( 'tokyo '' guitar teacher ',' er ')
Print (c2) # playing cards (color = 'Tokyo', number = 'guitar teacher', BA = 'ER')

2, queue: FIFO (First in the FIFO First OUT)
Import Queue
q = queue.Queue () # generates queue object
q.put ( 'first') # value added to the queue
q.put ( 'SECOND')
q.put ( 'THIRD')
Print (q.get ()) # value from the queue
Print (q.get ())
Print (q.get ())
Print (q.get ()) # If the value is taken over in the queue will wait until get the value from the queue stopped in situ

3, the deque deque
PS: queue does not support arbitrary position interpolation should
only end-interpolated (can not jump the queue)
# specific points: deque may interpolation index at any position
from the deque Collections Import

Q = the deque ([ 'A' , [ 'B'], [ 'C']])
Print (q.append (. 1)) ### None
Print (q.pop ()). 1 #
print (q) #deque ([ 'clam shell sea J', 2, 'A', [ 'B'], [ 'C']])
Print (q.popleft ()) # sea clamshell J
Print (Q .popleft ()) # 2
. 4, ordered dictionary: how is how to create a sequence of (about creation order)
from Collections Import OrderedDict
Old = OrderedDict ()
Old [ '. 1'] = '111' first key of
Old [ 'Y'] = 'EE'
Old [ 'Z'] = '333'
Print (Old)
for I in Old:
Print (I)
. 5, counter counts (present in the form of key-value pairs)
from Collections Import counter
S = 'abcdeabcdabcaba'
res = Counter(s)
Print (RES) #Counter ({ 'A':. 5, 'B':. 4, 'C':. 3, 'D': 2, 'E': 1})
2, time module:
three forms
1. ***** stamp
2. time formatter (used to display the posters)
3. structured time
ps: not straightforward timestamp formatting time, must be converted to a structured time, and then converted into a format time of
1, time stamp Import
print (the time.time ()) # seconds stamp
print (time.strftime ( '% Y-% m-% d% X')) # date, hour, minute
print ( the time.sleep (. 1))
Print (The time.strftime ( '% Y-M-% D%% H:% M:% S')) # date, hour, minute
print (time.strftime ( '% H: % m ')) # division
print (time.strftime ('% Y / % m ')) Years #
3, the structure of the time
print(time.localtime())
print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
import datetime
print(datetime.date.today()) # date>>>:年月日
print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
Print (res.month)
Print (res.day)
Print (res.weekday ()) # 0 for 0-6 day of the week Monday
print (res.isoweekday ()) # 1-7 7 is the day of the week on Sunday
(** ****)
date date Object target = +/- timedelta objects
timedelta target = +/- date object date object
current_time = datetime.date.today () # date object
timetel_t = datetime.timedelta (days = 7) # timedelta objects
res1 = current_time + timetel_t # date objects

Print (CURRENT_TIME - timetel_t)
Print (RES1-CURRENT_TIME)
# UTC time (gap 8 hours)
dt_today datetime.datetime.today = ()
= datetime.datetime.now dt_now ()
dt_utcnow = datetime.datetime.utcnow ()
Print (dt_utcnow, dt_now, dt_today)
. 3 # module random *****
Import Random

Print (the random.randint (1,6)) # Random a number range of integers take your provided comprising end-
print (random.random ()) # randomly decimal between 0-1
Print (the random.choice ([1,2,3,4,5,6])) # Yaohao randomly an element from the list
RES = [1,2,3,4,5,6]
random.shuffle (RES) # shuffling
print (res)
case:
uppercase letter lowercase alphanumeric
random digit verification 5 code
CHR
random.choice
Encapsulated into a function, the user would like to generate several generates several

DEF GET_CODE (n-):
# random string is empty
code = ''
for I in Range (n-): 5 cycles #
Mr # lowercase to uppercase random alphanumeric
upper_str = CHR (the random.randint (65, 90))
lower_str = CHR (the random.randint (97, 122))
random_int = STR (the random.randint (0,. 9))
# choose one of the above three randomly a random codes of a bit
code the random.choice + = ([upper_str, lower_str, random_int])
return code returned randomly drawn numbers #

RES GET_CODE = (. 5)
Print (RES) # 5 obtained random character a string
4, os module: module dealing with the operating system
      
os.makedirs ( '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.stat ( 'path / filename') get the file / directory information
os.system ( "bash command") to run shell commands, displayed directly
os.popen ( "bash command) .read ( ) run shell commands to get the results
os.getcwd () to get the current working directory, ie, the current python script work directory path
os.chdir ( "dirname") script to change the current working directory; cd at the equivalent of shell

os.path
os.path.abspath (path) Returns the path normalized absolute path
os.path.split (path) into the path directory and file name tuple returned
os.path.dirname (path) Returns the directory path of. In fact, os.path.split (path) of the first element
os.path.basename (path) Returns the last path of the file name. How path to / \ or end, it will return a null value. I.e. The os.path.split (path) of the second element
os.path.exists (path) path, if present, returns True; if the path does not exist, returns False
os.path.isabs (path) if the path is an 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
5. The SYS module: python interpreter module dealing with
sys.argv List command-line arguments, the first element is the path to the program itself *******
the sys.exit (n-) to exit the program, when the normal exit exit (0) error exit sys.exit (1)
sys.version to obtain the version of Python interpreter
sys.path return module search path, use the PYTHONPATH environment variable initialization value *****
sys.platform return to the operating system platform name










Guess you like

Origin www.cnblogs.com/Fzhiyuan/p/11210344.html