collections module, a time module, Random module, os module, sys module, a sequencing module, The subprocess module

A, collections module

1, other data types

  On the basis of built-in data types (str, dict, list, tuple, set) on, collections module also provides several types of additional data: Counter, deque, defaultdict, namedtuple and OrderedDict.

2, namedtuple (named tuple)

  ①, utensils name tuple represents a coordinate point

from collections import namedtuple
Point = namedtuple('Point',['x','y'])
p = Point(1, 2)
print(p)
# 输出
Point(x=1, y=2)

  Information ②, utensils name tuple record of a city

Collections namedtuple Import from 
City namedtuple = ( 'City', 'name Country Population coordinates') 
# The first is the class name, the second field is the name of each class. The latter may be the object of a number of iterations consisting of a string, or a string separated by spaces apart field names consisting of 
Tokyo City = ( 'Tokyo', 'JP', 36.933, (35.689722,139.691667)) 
Print (Tokyo) 
# output 
City (name = 'Tokyo', country = 'JP', population = 36.933, coordinates = (35.689722, 139.691667))

  ③, Format: namedtuple ( 'name', [Properties List])

3, deque (deque)

  ①, when using the list of data storage, access the elements by index quickly, but inserting and removing elements is very slow, because the list is linear memory, when a large amount of data, efficiency is very low insertion and deletion. deque in order to achieve efficient insertion and deletion of the two-way list for queues and stacks.

  ②, qeque addition to achieving list of append () and pop (), it also supports appendleft () and popleft (), so that you can be very efficient to add or delete elements of the head.

from collections import deque
q = deque(['a','b','c'])
q.pop()
q.append('x')
q.popleft()
q.appendleft('y')
print(q)
# 输出
deque(['y', 'b', 'x'])

  ③, deque supports insert () method, the interpolation may be in any position

from collections import deque
q = deque(['a','b','c'])
q.insert(1,'x')
print(q)
# 输出
deque(['a', 'x', 'b', 'c'])

4, OrderedDict (ordered list)

  When using dict, the key is out of order, when to do dict iteration, we can not determine the order key, if you want to keep the order key, you can use OrderedDict

from Collections Import OrderedDict 
D = dict ([( 'A',. 1), ( 'B', 2), ( 'C',. 3)]) 
Print (D) 
OD = OrderedDict ([( 'A',. 1) , ( 'B', 2), ( 'C',. 3)]) 
Print (OD) 

# python2 result 
>>> D 
{ 'A':. 1, 'C':. 3, 'B': 2} 
> OD >> 
OrderedDict ([( 'A',. 1), ( 'B', 2), ( 'C',. 3)]) 

# Python3 result 
>>> D 
{ 'A':. 1, 'B': 2, 'C':}. 3 
>>> OD 
OrderedDict ([( 'a',. 1), ( 'B', 2), ( 'C',. 3)]) 

# to python3 list optimized, so that he It appears to be orderly

5, defaultdict (default value dictionary)

  ①, the following values ​​[11, 22, 33, 44, 55, 66, 77, 88, 99, 90], all values ​​greater than the stored first key 66 to the dictionary, the 66 will be less than the value stored to the second key value in

# 原生字典解决方案
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = {}
for value in  values:
    if value>66:
        if my_dict.__contains__('k1'):
            my_dict['k1'].append(value)
        else:
            my_dict['k1'] = [value]
    else:
        if my_dict.__contains__('k2'):
            my_dict['k2'].append(value)
        else:
            my_dict['k2'] = [value]
print(my_dict)
# 输出
{'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]}

# defaultdict解决方案
from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list)
for value in  values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict)
# 输出
defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

  ②, use dict, if the referenced key is not present throws KeyError. If you want the key does not exist, returns a default value, you can use defaultdict

from Collections Import a defaultdict 
dd = a defaultdict (the lambda: 'N / A') 
dd [ 'key1'] = 'ABC' 
Print (dd [ 'key1']) 
Print (dd [ 'key2']) 
# output 
ABC 
N / A 
the return value of the presence of key # key, return to the default value when you set key does not exist

6, Counter (count)

  Counter object class is used to track the number of times of occurrence, he is an unordered type container to form keys of the dictionary memory, wherein the elements as key, as its count value. Count value may be any integer (including 0 and negative numbers). Counter class and other languages ​​bags or multisets very similar.

from collections import Counter
c = Counter('abcdeabcdabcaba')
print(c)
# 输出
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Second, the time module

1, represents a time of three ways

  ①, timestamp (timestamp): representation is from January 1970 00:00:00 1st offset press in seconds.

  ②, the formatted time string (format string): 1999-12-06

  ③, tuple (struct_time): struct_time tuple total of nine elements (year, month, day, hour, minute, second, in the first weeks of the year, days of the year, etc.)

2, import time import time module

3, time.time () Returns the timestamp

4, the time string

import time

print(time.strftime("%Y-%m-%d %X"))
print(time.strftime("%Y-%m-%d %H-%M-%S"))
# 输出
2019-07-18 22:12:55
2019-07-18 22-12-55

5, time-tuple: localtime a timestamp to the current time zone to struct_time

import time
print(time.localtime())
# 输出
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=22, tm_min=21, tm_sec=22, tm_wday=3, tm_yday=199, tm_isdst=0)

6, the computer is able to identify the timestamp of the time; time string is one can read time; tuple is used to operate the time

7, the conversion between several formats

 

8, datatime module

datetime Import 

# custom date 
RES = datetime.date (2019, 7, 15) 
Print (RES) # 2019-07-15 

# get local time 
# date 
now_date = datetime.date.today () 
Print (now_date) # 2019-07-01 
when the year, month, day, hour # 
now_time = datetime.datetime.today () 
Print (now_time) # 2019-07-01 17: 46: 08.214170 

# whether date, year, month, day, hour or objects you can call the following method to get targeted data 
# datetime objects, for example to 
print (now_time.year) # obtaining Year 2019 
Print (now_time.month) # Gets month 7 
Print (now_time.day) access to day # 1 
Print (now_time.weekday ( )) # get the week (weekday week 0-6) 0 means Monday 
print (now_time.isoweekday ()) # get the week (weekday 1-7 weeks) 1 said Monday 

# timedelta objects 
# may perform arithmetic operations on time 
import datetime 

# obtain local date date
= datetime.date.today tday () 
# define the operating time day = 7 i.e. the object can be added to another time or reduce 7:00 7 days 
TDELTA = the datetime.timedelta (Days =. 7) 

# printing today's date 
print ( 'Today date: {} 'format (tday) ) # 2019-07-01. 
date seven days after the # printing 
print (' pushed back seven days from today:. {} 'format (tday + tdelta)) # 2019-07 -08 
# summary: the relationship between the object and the date timedelta

Three, random module

1, several methods

Print (the random.randint (1,6)) 
# take a random integer number in the range you provided, comprising inclusive 
Print (random.random ()) 
# randomly floating point number between 0-1 
Print (The random.choice ([1, 2, 3, 4, 5, 6])) 
# wave number randomly from a list of elements 
RES = [1, 2, 3, 4, 5, 6] 
random.shuffle (RES) 
Print (RES) 
# reshuffle

 2, a random codes

'' '' '' 
Import Random 

'' ' 
random n-bit codes 
uppercase letters, lowercase letters, numbers, each number is not limited to 
the package as a function the user wants to generate several generates several 
' '' 
GET_CODE DEF (n-): 
    code = '' 
    for I in Range (n-): 
        # generates random uppercase letters, lowercase letters, numbers 
        upper_str = CHR (the random.randint (65, 90)) 
        lower_str = CHR (the random.randint ( 97, 122)) 
        random_int = STR (the random.randint (0,. 9)) 
        # from above in three randomly selects a random codes of a bit 
        code + = random.choice ([upper_str, lower_str, random_int]) 
    code return 
RES = GET_CODE (. 4) 
Print (RES)

Four, os module

1, os operating system and the module is a module dealing

os Import 
base_dir = os.path.dirname (__ file__) 
MOVIE_DIR = os.path.join (base_dir, 'teachers' works') 
movie_list = os.listdir (MOVIE_DIR) 
the while True: 
    for i, J in the enumerate (movie_list, 1 ): 
        Print (i, J) 
    Choice = the iNPUT ( 'you want to see who's ah (today's hot search: tank teacher) >>>:') Strip (). 
    iF choice.isdigit (): # determines whether the user input is a pure digital 
        choice = int (choice) # pass an int 
        if choice in range (1, len (movie_list) +1): # determine whether the number of elements in the list within the range of 
            # obtain a user wants to see the file name 
            target_file = movie_list [-Choice. 1] 
            # splice file absolute path 
            target_path = the os.path.join (MOVIE_DIR, target_file) 
            with Open (target_path, 'R & lt', encoding = 'UTF-. 8') AS F:
                Print (f.read ()) 


 
os.mkdir ( 'Tank teacher selection') # automatically create a folder
print (os.path.exists (r'D: \ Python project \ day16 \ rion teacher selection ')) # determine whether a file exists 
print (os.path.exists (r'D: \ Python project \ day16 \ teacher who works \ tank teacher .txt ')) # determine whether a file exists 
print (os.path.isfile (r'D: \ Python project \ day16 \ tank teacher selection')) # only You can not determine whether a file folder 
print (os.path.isfile (r'D: \ Python project \ day16 \ teacher who works \ tank teacher .txt ')) # can not determine whether a file folder 

os.rmdir ( r'D: \ Python project \ day16 \ teachers 'work') # can only delete empty folders 

Print (os.getcwd ()) 
Print (os.chdir (r'D: \ Python project \ day16 \ teachers works ')) # Change directory currently resides 
Print (os.getcwd ()) 

# get the file size 
print (os.path.getsize (r'D: \ Python project \ day16 \ teacher who works \ tank teacher .txt' )) # bytes in size 
with open (r'D: \ Python project \ day16 \ teacher who works \ tank teacher .txt ', encoding =' UTF-8 ') AS f: 
    Print (len (f.read()))

Five, sys module

SYS Import 
# sys.path.append () # to add a path to the environment variable system 
# Print (sys.platform) 
# Print (sys.version) # Python interpreter version 

print (sys.argv) # command line boot file can be done to verify the identity of the 
IF len (sys.argv) <= 1: 
    Print ( 'Please enter your username and password') 
the else: 
    username = sys.argv [1] 
    password = sys.argv [2] 
    IF username = = 'Jason' and password == '123': 
        Print ( 'Welcome') 
        # py this current document logic code 
    the else: 
        Print ( 'user does not exist to perform the current file')

Six, sequencing module

"" " 
Serialization 
    sequence: string 
    sequence of: converting a character string into other data types during 

the data string must be written to the file 
-based data transmission network must be binary 

    d = { 'name': ' jason'} Dictionary 
    str (d) 

    a sequence of: other types of data translated into strings during 
    deserialization: string converted to other data types 

    json module (******) 
        All languages supported json format 
        data types supported seldom string dictionary listing integer tuple (converted into a listing) Boolean 


    pickle module (****) 
        only supports Python 
        Python support all data types 
"" " 
Import JSON 
" "" 
dumps: the sequence of other types of data transfer into a formatted string json 
loads: deserialization json string format to convert into other data types 

the dump Load 
"" " 
D = {" name ":" Jason "} 
Print (D) 
RES = json.dumps (d) # json format string must be double quotes >>>: '{ "name": "jason"}'
Print (RES, type (RES)) type(res))
res1 = json.loads(res)
Print (RES1, type (RES1)) 

D = { "name": "Jason"} 

with Open ( 'UserInfo', 'W', encoding = 'UTF-. 8') AS F : 
    The json.dump (D, F) # string and automatically written to the file attached 
with Open ( 'UserInfo', 'R & lt', encoding = 'UTF-. 8') AS F: 
    RES = the json.load (F) 
    Print ( RES, type (RES)) 


with Open ( 'UserInfo', 'W', encoding = 'UTF-. 8') AS F: 
    The json.dump (D, F) # string and installed automatically written to file 
    The json.dump ( d, f) # automatically written to the file and the string attached 

with Open ( 'UserInfo', 'R & lt', encoding = 'UTF-. 8') AS F: 
    RES1 = the json.load (F) is not capable of multiple anti-sequence # of 
    RES2 = the json.load (F) 
    Print (RES1, type (RES1)) 
    Print (RES2, type (RES2)) 


with Open ( 'userinfo','w',encoding='utf-8') as f:
    json_str = json.dumps(d)utf-8') as f:
    json_str1 = json.dumps(d)
    f.write('%s\n'%json_str)
    f.write ( '% S \ n-' json_str1%) 


with Open ( 'UserInfo', 'R & lt', encoding = 'UTF-. 8') AS F: 
    for in Line F: 
        RES = json.loads (Line) 
        Print ( RES, type (RES)) 
T = (1,2,3,4) 
Print (json.dumps (T)) 


D1 = { 'name': 'Zhu Zhijian'} 
Print (json.dumps (D1, ensure_ascii = False) ) 







the pickle 
Import the pickle 
D = { 'name': 'Jason'} 
RES = the pickle.dumps (D) # object directly converted into binary 
Print (the pickle.dumps (D)) 
RES1 = the pickle.loads (RES) 
Print (RES1 , type (RES1)) 

"" " 
when the operation of the file with the file open mode pickle must be pattern b 
" "" 
with open ( 'userinfo_1', 'WB') AS F: 
    the pickle.dump (D,f)

with open('userinfo_1','rb') as f:
    res = pickle.load(f)
    print(res,type(res))

Seven, subprocess module

"" " 
1. The user connected through a network you this computer 
2. The user input corresponding to a command based on the network on which a program your computer 
3 acquires the user command to execute the user command which subprocess 
4. based on the results of the network and then sent to the user 
so that the user remotely operating the operation you realize this computer 
"" " 
the while True: 
    cmd = the INPUT ( 'cmd >>>:') Strip (). 
    Import subprocess 
    obj = subprocess.Popen ( cmd, the shell = True, subprocess.PIPE = stdout, stderr = subprocess.PIPE) 
    # Print (obj) 
    Print ( 'command returns the correct result stdout', obj.stdout.read (). decode ( 'GBK')) 
    Print ( 'command returns the error message stderr', obj.stderr.read (). decode ( 'gbk'))

  

 

Guess you like

Origin www.cnblogs.com/DcentMan/p/11210605.html