Python basics summary (short notes)

Python is a cross platform computer programming language. It is an object-oriented dynamic type language. Notes include the basic skills of compiling and installing python, python list, dictionary, tuple, file operation and other commands.

◆ compiling and installing Python

Python development environment installation and configuration is very simple. If it is a Linux system, python environment will be integrated and installed by default. Python executable files are placed in the / usr/local/bin directory, and library functions are installed in the / usr/local/python directory. Because binary installation is not easy, the source code will be used to compile and install Python interpreter

1. First install the gcc compiler and the dependent packages needed to compile Python

[root@localhost ~]# yum -y install gcc zlib zlib-devel openssl openssl-devel libffi-devel wget
Package gcc-4.8.5-36.el7.x86_64 already installed and latest version
Package zlib-1.2.7-18.el7.x86_64 already installed and latest version
Package zlib-devel-1.2.7-18.el7.x86_64 already installed and latest version
Package openssl-1.0.2k-16.el7.x86_64 already installed and latest version
Package openssl-devel-1.0.2k-16.el7.x86_64 already installed and latest version
Package libffi-devel-3.0.13-18.el7.x86_64 already installed and latest version
Nothing to do

2. Download Python source code, and execute nmake command in turn to complete the whole compilation process. If the waiting time is long, skip it

[root@localhost ~]# yum install -y readline
[root@localhost ~]# wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz
[root@localhost ~]# tar -xzvf Python-3.8.0.tgz -C /usr/src/
[root@localhost ~]# cd /usr/src/Python-3.8.0/
[root@localhost ~]# ./configure --prefix=/usr/local/python3
[root@localhost ~]# make && make altinstall

3. Copy the python header file to the system standard directory to avoid that you can't find the required header file when using Python directly

[root@localhost ~]# cd /usr/local/python3/include/python3.8
[root@localhost ~]# cp -a ./* /usr/local/include/

4. Then we backup the old version of Python and create a symbolic link to the new version

[root@localhost ~]# cd /usr/bin/
[root@localhost bin]# mv python python.old
[root@localhost bin]# ln -s /usr/local/python3/bin/python3.8 /usr/local/bin/python
[root@localhost bin]# cp -a /usr/local/python3/bin/python3.8 /usr/bin/python

5. Because YUM warehouse is developed in Python, it needs to be replaced here to avoid the conflict between Python 2 and python 3

[root@localhost ~]# vim /usr/bin/yum
#! / usr/bin/python2.7 ← change Python to python2.7 here

[root@localhost ~]# vim /usr/libexec/urlgrabber-ext-down
#! / usr/bin/python2.7 ← change Python to python2.7 here

6. Finally, test whether the new Python version is effective, and then use the YUM command to see whether it is effective. Everything is normal here

[root@localhost bin]# python
Python 3.8.0 (default, Nov  9 2019, 01:48:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

7. Install the pip package management tool, which provides the functions of finding, downloading, installing and uninstalling Python packages

[root@localhost ~]# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
[root@localhost ~]# python get-pip.py
[root@localhost ~]# echo "alias pip=\"/usr/local/python3/bin/pip\"" >> /etc/profile
[root@localhost ~]# pip --version
pip 19.3.1 from /usr/local/python3/lib/python3.8/site-packages/pip (python 3.8)

Package Python as EXE: we install the pyinstaller tool to see if we can package independent executable files

[root@localhost ~]# pip install pyinstaller
[root@localhost ~]# pip show pyinstaller
[root@localhost ~]# pyinstaller -F ./lyshark.py
[root@localhost ~]# pyinstaller -F -w -i lyshark.ico lyshark.py  # -w: do not prompt the console

Compile Python to exe: you can compile Python to exe executable program by using python. Note that compilation is not packaging

C:/> python -m cython -3 --embed -o lyshark.c lyshark.py

C:/> cl /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I"D:\python\include" /Tc lyshark.c /DWIN32
C:/> link lyshark.obj /SUBSYSTEM:CONSOLE /MACHINE:X64 /LIBPATH:"D:\python\libs"
C:/> link lyshark.obj /SUBSYSTEM:WINDOWS /MACHINE:X64 /LIBPATH:"D:\python\libs" /ENTRY:"wmainCRTStartup"

Compile Python to ELF: ELF is the file running format under Linux system. We can compile Python to ELF file

[root@localhost ~]# yum install -y epel-release
[root@localhost ~]# yum install -y python-pip
[root@localhost ~]# yum install -y python-dev*
[root@localhost ~]# pip install cython

[root@localhost ~]# cython lyshark.py --embed
[root@localhost ~]# gcc `python-config --cflags` `python-config --ldflags` lyshark.c -o lyshark


◆ Python input and output

Input and output are the things that exist in any programming language. The essence of computer is input and output. Before learning python, you must first learn input and output. Python's input and output are very simple. If you input, you can directly use the input function. If you output, you can use the print function

Usage of standard input: the default reception is treated as a string. If you need a number, you need to cast it to int() to a number

>>> name = input("Please enter your name:")
//Please enter your name: lyshark
>>> print("Hello " + name)
Hello lyshark
>>> age = input("Please enter your age:")
//Please enter your age: 22
>>> type(age)
<class 'str'>
>>> age1 = input("Please enter your age:")
>>> age1 = int(age1)  #Cast here
>>> type(age1)
<class 'int'> 

Password input special method: when entering a password, you need to use the getpass method in the getpass module, that is:

import getpass
  
#Assign user input to pwd variable
 pwd = getpass.getpass("please enter password:")
Please input a password:

#Print input
print(pwd)

Simple format output: by using the print function, we can achieve simple format output

>>> string = "hello lyshark"
>>> print(string)
hello lyshark
>>> print(string,) # Don't let it wrap
>>> print('hello', end = " ")
>>>
>>> string = "the length of (%s) is %d"  %("hello lyshark",len("hello lyshark"))
>>> print(string)
the length of (hello lyshark) is 13
>>>
>>> string = "hello {} --> age {}".format("lyshark",22)
>>> print(string)
hello lyshark --> age 22
>>>
>>> string = "i am %(age).2f" %{"age":22}
>>> print(string)
i am 22.00

Format conversion output: format output decimal, hexadecimal, octal

>>> import math

>>> nHex=0x20
>>> print("Hexadecimal=%x,Decimal system=%d,Octal number system=%o"%(nHex,nHex,nHex))
//Hex = 20, decimal = 32, octal = 40
>>>
>>> print("PI=%F"%math.pi)
PI=3.141593
>>> print("PI=%10.2f"%math.pi)
PI=      3.14
>>> print("PI=%-10.2f"%math.pi)
PI=3.14

Detailed usage of format:

>>> print("i am {0}, age {1}, really {0}".format("lyshark",22))
i am lyshark, age 22, really lyshark
>>>
>>> print("i am {name}, age {age}".format(**{"name":"lyshark","age":"22"}))
i am lyshark, age 22
>>>
>>> temp = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
>>> print(temp)
i am 1, age 2, really 3
>>>
>>> temp = "i am {:s}, age {:d}, money {:f}".format("lyshark", 18, 8.1)
>>> print(temp)
i am lyshark, age 18, money 8.100000
>>>
>>> temp = "%r %r %r %r"
>>> print(temp%(1,2,3,4))
1 2 3 4
>>>
>>> print("Website name:{name},address:{url}".format(name="myblog",url="www.baidu.com"))
//Website name: myblog, address: www.baidu.com
>>>
>>> site={"name":"myblog","url":"www.baidu.com"}
>>> print("Website name:{name} address:{url}".format(**site))
//Website name: myblog address: www.baidu.com
>>>
>>> my_list = ['myblog','www.baidu.com']
>>> print("Website name:{0[0]},address:{0[1]}".format(my_list))
//Website name: myblog, address: www.baidu.com


◆ Python simple operation

Operators are used to perform program code operations. They operate on more than one operand item. In Python, operators can be roughly divided into seven types: arithmetic operators, comparison operators, assignment operators, logical operators, bit operations, etc. the following examples will introduce the use skills of these operators in turn

Arithmetic operators: symbols used to process four operations. Arithmetic symbols are used in all programming languages

>>> num1 = 10
>>> num2 = 20
>>>
>>> num1 + num2
30
>>> num1 - num2
-10
>>> num2 % num1   # Modulo: returns the remainder of division
0
>>> num2 // num1 ×× round: returns the integer part of the quotient 
2
>>> num1 ** num2  # Power sign: returns num2 power of num1
100000000000000000000

Comparison operator: the result of the comparison operator is a logical value, either true or false

>>> num1 = 10
>>> num2 = 20
>>>
>>> num1 == num2
False
>>> num1 != num2
True
>>> num1 >= num2
False
>>> num1 <= num2
True

Assignment operator: the basic assignment operator is = (not equal sign, equal sign is = =), so the operator is often read last

>>> num1 = 10
>>> num2 = 20
>>>
>>> num1 = 10
>>> num1 += 10
20
>>> num1 -= 10
10

Bit operation symbol: in a program, bit operation is to directly operate the binary bits of an integer in memory

>>> a=60                      # 60 = 0011 1100 
>>> b=13                      # 13 = 0000 1101
>>> c=0 
>>>
>>> c= a & b                  # 12 = 0000 1100
>>> print("a And b: ",c)
a And b:  12
>>>
>>> c= a | b                  # 61 = 0011 1101 
>>> print("a or b: ",c)
a or b:  61
>>>
>>> c=a^b                     # 49 = 0011 0001
>>> print("a XOR b:",c)
a XOR b: 49
>>>
>>> c=a << 2                  # 240 = 1111 0000
>>> print("a Left shift 2",c)
a Left shift 2240

Other operators: other operators include common, logical operation, member operation, identity operation, etc

>>> num1 = 10
>>> num2 = 20
>>> num3 = 0
>>> list = [10,20,30,40,50]
>>>
>>> num1 and num3
0
>>>
>>> num1 in list      # Determine whether num1 is in the list
True
>>> num1 not in list
False
>>>
>>> num1 is num3      # Determine whether two identifiers are referenced from one object
True
>>> num1 is num2
False
>>> num1 is not num2
True

Rounding: rounding is used in some special cases

>>> import math
>>>
>>> math.ceil(3.14)
4
>>> round(3.14)
3


Python data types

The definition of data type in data structure is a set of values and a set of operations defined in this set of values. In Python, data types include numeric types, character type groups, lists, dictionaries, tuples, and other types. The following examples will introduce the use skills of these operators in turn

◆ type of value

Python supports int, float, bool and complex (complex). In Python, there is only one integer type, int, that is, long integer. Like most languages, the assignment and calculation of numeric types are very intuitive. For data exchange between numeric types, please refer to the following list:

int(x)              #Convert x to an integer  
long(x)             #Convert x to a long integer  
float(x)            #Convert x to a floating-point number  
complex()           #Create a complex number  
str(x)              #Convert object x to string  
repr(x)             #Convert object x to expression string  
eval(str)           #Used to evaluate a valid Python expression in a string and return an object  
tuple(x)            #Convert sequence s to a tuple  
list(x)             #Convert sequence s to a list  
chr(x)              #Convert an integer to a character  
unichr(x)           #Convert an integer to a Unicode character  
ord(x)              #Convert a character to its integer value  
hex(x)              #Convert an integer to a hexadecimal string  
oct(x)              #Convert an integer to an octal string  

Integer to other value: use the conversion command to convert an integer to another value

>>> temp=100
>>>
>>> float(temp)
100.0
>>> complex(temp)
(100+0j)
>>> str(temp)
'100'

Integer conversion character: use the conversion command to convert an integer to a character

>>> temp=100
>>>
>>> chr(temp)
'd'
>>> ord(chr(temp))
100

Base conversion: use conversion command to implement base conversion

>>> temp=100
>>>
>>> hex(temp)
'0x64'
>>> oct(temp)
'0o144'

◆ string type

String is a collection of characters. Python supports string as a data type and provides some rich string processing functions. In the following list are string operation functions supported by python. Next, we will find several common string functions for demonstration

str.capitalize()    #Capitalize the first letter of a string
str.title()         #Capitalize each word in the string
str.upper()         #Change string to uppercase
str.lower()         #Make string lowercase
str.index()         #Find the string corresponding to the index
str.find()          #Find the string corresponding to the index
str.count()         #Find out the number of occurrences of elements in a string
str.format()        #It's also a format
str.center()        #What characters to fill from both sides of the string
str.join()          #Connect string with str as separator
str.split()         #What is the separator to separate strings
str.strip()         #Remove the spaces on both sides of the string
str.replace()       #Search and replace
str.isupper()       #Determine whether it is capitalized
str.islower()       #Determine whether it is lowercase
str.isalnum()       #Determine whether it is alphanumeric
str.isalpha()       #Determine whether it is a letter underline
str.isdigit()       #Judge whether it is a number
str.isspace()       #Judge whether it is empty
str.startswith()    #Find out what character elements start with
str.endswith()      #Find out what character elements end with

Capitalize: use the capitalize() function to capitalize the initial of a specified string

>>> str="hello lyshark"
>>>
>>> str.capitalize()
'Hello lyshark'

Capitalize all: use the title() function to capitalize each word in the string

>>> str="hello lyshark"
>>>
>>> str.title()
'Hello Lyshark'

Find string: use the index() function to find the index number of the specified string. If it doesn't exist, an error will be reported

>>> str="hello lyshark"
>>>
>>> str.index("hello")
0
>>> str.index("lyshark")
6
>>> str.index("mk")
ValueError: substring not found

Find string: use the find() function to find the index number of the specified string. If it does not exist, return - 1

>>> str="hello lyshark"
>>>
>>> str.find("hello")
0
>>> str.find("lyshark")
6
>>> str.find("mk")
-1

Count the number of string Occurrences: count the number of occurrences of the specified string using the count() function

>>> str="hello lyshark"
>>>
>>> str.count("h")
2
>>> str.count("l")
3
>>> str.count("hello")
1
>>> str.count("mk")
0

String filling: use the center() function to fill the content on both sides of the specified string

>>> str="hello lyshark"
>>>
>>> str.center(20,'*')
'***hello lyshark****'
>>>
>>> print(str.center(50,'-'))
------------------hello lyshark-------------------

String connection: use the join() function to connect the specified characters in the sequence to generate a new string

>>> str="-"
>>> seq=("hello","lyshark","welcome")
>>>
>>> print(str.join(seq))
hello-lyshark-welcome

>>> list =['1','2','3','4','5']
>>> print(''.join(list))
12345

>>> 'kill %s' % ' '.join(['1024','2234'])

Cut string: use the split() function to divide a string and save it as a list

>>> str="hello-lyshark-welcome"
>>>
>>> str.split("-")
['hello', 'lyshark', 'welcome']

Remove the spaces on both sides of the string: use the strip() function to remove the spaces on both sides of the specified string

>>> str="    hello      lyshark       "
>>> str
'    hello      lyshark       '
>>>
>>> str.strip()
'hello      lyshark'

Remove the space on both sides of the string (left / right): use str.lstrip() function to remove the space on the left of the string

>>> str="    hello      lyshark       "
>>>
>>> str.rstrip()
'    hello      lyshark'
>>>
>>> str.lstrip()
'hello      lyshark       '
>>>

String find replace: use the replace() function to find and replace the specified string

>>> str="hello lyshark"
>>> str
'hello lyshark'
>>>
>>> str.replace("lyshark","mkdirs")
'hello mkdirs'

Determine whether it is uppercase: use isupper() function to determine whether the specified string is uppercase

>>> str="LYSHARK"
>>> str1="lyshark"
>>>
>>> str.isupper()
True
>>> str1.isupper()
False

Find the beginning and the end: use the startswitch() function to find the character elements that start with a specified letter

>>> str="hello lyshark welcome"
>>>
>>> str.startswith("hello")
True
>>> str.startswith("lyshark")
False
>>>
>>> str.startswith("lyshark") or str.endswith("welcome")
True
>>> str.startswith("lyshark") and str.endswith("welcome")
False

◆ type of list

List is the most basic data structure in Python, and it is also the most commonly used one. Each element in the list is assigned a number - its location or index. The first index is 0, the second index is 1, and so on. Next, we will find several common list operation functions for demonstration

list.insert()       #Insert an element before specifying the index position in the list
list.append()       #Insert at end of list
list.remove()       #Delete the specified element
list.pop()          #If no index is specified, the last element will pop up, and the returned result is the corresponding element of the pop-up index
list.copy()         #Shallow copy, only the first layer is copied. If there is a nested sequence, it will not be copied. Copy is required to import the copy module
list.extend()       #Merging another list is not appending
list.index()      #Index location of elements in the list
list.count()        #Count the number of elements in the list
list.reverse()      #Reverse order
list.sort()         #Cannot sort numbers and strings together
list1 + list2       #Merge two lists and return a new list without modifying the original list
list * N            #Repeat the list N times to return a new list

Append data to the list: use the append() function to append and write several data to the specified list

>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>>
>>> list.append(4)
>>> list.append(5)
>>> list.append(6)
>>>
>>> list
[1, 2, 3, 4, 5, 6]

Insert data into the list: use the insert() function to insert several data into the specified list to the specified location

>>> list = ["admin","lyshark"]
>>> list
['admin', 'lyshark']
>>>
>>> list.insert(1,"python")
>>> list
['admin', 'python', 'lyshark']
>>>
>>> list.insert(2,"ruby")
>>> list.insert(2,"ruby")
>>> list
['admin', 'python', 'ruby', 'ruby', 'lyshark']

Modify the specified data: modify the field value of the specified element by using the method of name [] variable assignment

>>> list
['admin', 'python', 'ruby', 'ruby', 'lyshark']
>>> list[0]="mkdirs"
>>> list
['mkdirs', 'python', 'ruby', 'ruby', 'lyshark']
>>>
>>> list[3]="pip"
>>> list
['mkdirs', 'python', 'ruby', 'pip', 'lyshark']

Delete the specified data: use the remove() function to delete the specified data, or use the del() function to delete

>>> list
['mkdirs', 'python', 'ruby', 'pip', 'lyshark']
>>> 
>>> del list[2]                             #Delete element by subscript
>>> list
['mkdirs', 'python', 'pip', 'lyshark']
>>> 
>>> list.remove("python")                   #Delete the specified element
>>> list
['mkdirs', 'pip', 'lyshark']
>>> 
>>> list.pop()                              #Delete the last element of the list
'lyshark'
>>> list.pop()
'pip'
>>> list
['mkdirs']

Extend a list: use the extend() function to append one list to the next

>>> list1 = ["admin","guest","lyshark"]
>>> list2 = [1,2,3]
>>>
>>> list1.extend(list2)
>>> list1
['admin', 'guest', 'lyshark', 1, 2, 3]

Shallow Copy list: use the copy() function to implement shallow Copy of the list

>>> list1
['admin', 'guest', 'lyshark', 1, 2, 3]
>>>
>>> list1_copy = list1.copy()
>>> list1_copy
['admin', 'guest', 'lyshark', 1, 2, 3]

Count the number of elements: use count() function to count the number of elements in the list

>>> list = ["admin","admin","lyshark","mkdirs"]
>>>
>>> list.count("admin")
2
>>> list.count("mkdirs")
1

Forward and reverse sorting: use the sort() reverse() function to sort the specified list elements

>>> list = ["admin","python","ruby","1","3","6","9"]
>>> list
['admin', 'python', 'ruby', '1', '3', '6', '9']
>>>
>>> list.sort()          #Forward sort, element type must be consistent
>>> list
['1', '3', '6', '9', 'admin', 'python', 'ruby']
>>>
>>> list
['1', '3', '6', '9', 'admin', 'python', 'ruby']
>>> list.reverse()          #Reverse sort, element types must be consistent
>>> list
['ruby', 'python', 'admin', '9', '6', '3', '1']

Get element subscript: use index() function to get element subscript

>>> list
['ruby', 'python', 'admin', '9', '6', '3', '1']
>>>
>>> list.index("admin")
2
>>> list.index("1")
6

Slice of list: use [] to realize various slice operations of list

>>> list=[1,2,3,4,5,6,7,8,9,0]
>>>
>>> list[1:4]              #Remove the elements of subscripts 1-4, excluding 4
[2, 3, 4]
>>>
>>> list[1:-1]             #Remove subscript 1 to - 1, excluding - 1
[2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> list[1:]               #Take the subscript from 1 to the last data
[2, 3, 4, 5, 6, 7, 8, 9, 0]
>>>
>>> list[:]                #Take out all elements
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> list[0::2]             #2 spaces at a time when taking elements
[1, 3, 5, 7, 9]

Delete data by sharding: use sharding to clear the data in the specified list

>>> list
[123, 111, 111, 111, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list[0:3]
[123, 111, 111]
>>>
>>> list[0:3]=[]            #Replace subscript 0-3 with null, excluding 3
>>> print(list)
[111, 8, 7, 6, 5, 4, 3, 2, 1]
>>>

Implementation of nested list: two lists are declared at one time and associated with data name

>>> list1,list2 = [[1,"a","b"],[2,"a","b"]]
>>>
>>> print(list1)
[1, 'a', 'b']
>>> print(list2)
[2, 'a', 'b']

Find element and modify (1): find the specified element in the list and modify it, only the first time found

[root@localhost]# cat test.py

#!/usr/bin/python
name = [1,2,3,4,5,1,5,6]
if 1 in name:
    num_of_ele = name.count(1)
    position_of_ele = name.index(1)
    name[position_of_ele] = 888
    print(name)

[root@localhost]# python test.py 
[888, 2, 3, 4, 5, 1, 5, 6]

Find elements and modify (2): find the specified elements in the list, modify them in batch, and modify all

[root@localhost]# cat test.py

#!/usr/bin/python
name = [1,2,3,4,5,1,5,6]

for i in range(name.count(1)):
    ele_index = name.index(1)
    name[ele_index] = 8888888
print(name)

[root@localhost]# python test.py
[8888888, 2, 3, 4, 5, 8888888, 5, 6]

Type of dictionary

A dictionary is another variable container model, which can store any type of object. A dictionary is a data type that uses key value pairs. Each key value (key = > value) in the dictionary uses a colon as the separator, while the key value pairs and key value pairs are separated by commas. The whole dictionary is included in curly braces, and the dictionary has two features. The first feature is that the data in the dictionary is disorderly stored, and the second feature is that The key in the sex dictionary must be unique, so the key is naturally de duplicated. The following are the format declarations of the dictionary:

person = {"name": "lyshark", "age": 22}
person = dict({"name": "lyshark", "age": 22})

info = {
    'stu1': "Taka Kato",
    'stu2': "Yui Hatano",
    'stu3': "Xiao zemaria",
}

Dictionaries need to use dictionary specific operation functions. The common functions of dictionaries are as follows. I will use different examples to illustrate later

dict.get(key)       #Get the value of a key
dict.has_key(key)   #Judge whether the dictionary has this key. It has been abolished in Python 3. Use in to judge
dict.keys()         #Return all key s as a list
dict.values()       #Return all value s as a list
dict.items()        #The key value of the dictionary is divided into tuples, and all tuples form a list
dict.pop(key)       #Pop up a key value
dict.popitem()      #Pop key value randomly
dict.clear()        #Clear all elements in dictionary
dict.copy()         #Dictionary copy, d2=d1.copy() is shallow copy, if deep copy needs copy module
dict.fromkeys(s)    #Generate a new dictionary
dict.update(key)    #Merge a dictionary into the current dictionary
dict.iteritems()    #To generate a key value iterator, you can use next() to take down a key value
dict.iterkeys()     #Generate key iterator
dict.itervalues()   #Generate values iterator

Add Dictionary: on the basis of info dictionary, add a field info["stu4"] = "Cang teacher"

>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>> info["stu4"] = "Aoi Sora"
>>>
>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}

Modify Dictionary: on the basis of info dictionary, modify stu1: Kato hawk to stu1: golden finger

>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}
>>>
>>> info["stu1"] = "Golden finger"
>>> info
{'stu1': 'Golden finger', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}

Delete Dictionary: on the basis of info dictionary, delete several dictionaries. The following provides a variety of deletion methods

>>> info
{'stu1': 'Golden finger', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}
>>>
>>> info.pop("stu1")        #Delete by pop function
'Golden finger'
>>> info
{'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}
>>>
>>> del info["stu4"]        #Delete by del command
>>> info
{'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> info.popitem()          #Randomly delete elements
('stu3', 'Xiao zemaria')

Search Dictionary: on the basis of info dictionary, several query tasks are completed, and several methods are provided here

>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> "stu1" in info          #Standard query method
True
>>>
>>> info.get("stu1")        #Use get function to query
'Taka Kato'
>>>
>>> info["stu2"]
'Yui Hatano'

Update Dictionary: on the basis of info dictionary, update the contents of dictionary, and merge temp dictionary and info dictionary

>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> temp = {1:2,"stu4":"Aoi Sora"}
>>>
>>> info.update(temp)
>>> info
{'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 1: 2, 'stu4': 'Aoi Sora'}

Traversal Dictionary: there are two kinds of dictionary traversal methods. The second one is recommended because it is the fastest

>>>Info = {'stu1': 'Kato Hawk','stu2 ':' potono's lichen ','stu3': 'little zemaria'}
>>>
>>> for keys,values in info.items():
...     print(keys,values)
...
stu1 Kato Hawk
 stu2 potono
 stu3 little zemaria

>>> for keys in info:
...     print(keys,info[keys])
...
stu1 Kato Hawk
 stu2 potono
 stu3 little zemaria

Index Dictionary: the dictionary also supports the way of index to obtain the elements in the dictionary, only the key must be used as the index

>>> info = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> info['stu2']
'Yui Hatano'
>>>
>>> len(info)
3
>>>
>>> dict = {"Full name":"Taka Kato","Score":[98,99,87]}
>>>
>>> dict["Full name"]
'Taka Kato'
>>> dict["Score"]
[98, 99, 87]
>>> dict["Score"][2:]
[87]

Dictionary unpacking: decomposes a dictionary into independent tuples and assigns tuples to other variables

>>> dict = {"Full name":"Taka Kato","Score":[98,99,87]}
>>> t1,t2 = dict.items()
>>>
>>> print(t1)
('Full name', 'Taka Kato')
>>> print(t2)
('Score', [98, 99, 87])
>>>
>>> k1,k2 = {"x":100,"y":200}
>>> print(k1)
x

Merge list into Dictionary: combine two lists into a dictionary, where list1 is key and List2 is values

>>> dict = {}
>>> list = [100,200,300,400,500]
>>> head = ["MemTotal","MemFree","Cached","SwapTotal","SwapFree"]
>>>
>>> for (keys,values) in zip(head,list):
...     dict[keys] = values
...
>>> dict
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
>>>
>>> dict(map(lambda x,y:[x,y],head,list))
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
>>>
>>> dict(zip(head,list))
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}

Dictionary key value adjustment: the key in the dictionary and the value in the dictionary are adjusted

>>> {key:value for key,value in zip(head,list)}
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}

>>> {value:key for key,value in zip(head,list)}
{100: 'MemTotal', 200: 'MemFree', 300: 'Cached', 400: 'SwapTotal', 500: 'SwapFree'}

Dictionary split into lists: split a complete dictionary into two lists

>>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>> keys= dict.keys()
>>> values = dict.values()
>>>
>>> print("keys:{}".format(keys))
keys:dict_keys(['stu1', 'stu2', 'stu3'])
>>>

>>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> keys,values = zip(*dict.items())
>>> print("Keys:",str(keys))
Keys: ('stu1', 'stu2', 'stu3')

>>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'}
>>>
>>> keys = []
>>> values = []
>>> items = dict.items()
>>> for x in items:
...     keys.append(x[0]),values.append(x[1])
...
>>> print(str(keys))
['stu1', 'stu2', 'stu3']

Dictionary merge and copy: merges dictionaries, but overwrites the original key value when there is the same key

>>> dict1 = {"x":1,"y":2}
>>> dict2 = {"a":3,"b":4}
>>> dict3 = {}
>>>
>>> dict3 = {**dict1,**dict2}
>>> print(dict3)
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
>>>
>>> dict3.update(dict1)
>>> dict3.update(dict2)
>>> print(dict3)
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
>>>
>>> import copy
>>> n1 = {"k1": "wu", "k2": 123, "k3": ["lyshark", 456]}
>>> n2 = {}
>>>
>>> n2 = copy.deepcopy(n1)
>>> print(n2)
{'k1': 'wu', 'k2': 123, 'k3': ['lyshark', 456]}

Complex table data storage:

>>> dict1 = {"name":"admin","age":19,"salary":3000,"address":"beijing"}
>>> dict2 = {"name":"guest","age":20,"salary":4000,"address":"shanghai"}
>>> dict3 = {"name":"lyshark","age":21,"salary":5000,"address":"shenzhen"}
>>> table = [dict1,dict2,dict3]

# Used to get the specified field data of the specified person
>>> print(table[1].get("name"))
guest
>>> print(table[2].get("address"))
shenzhen

# Print everyone's name in the form
>>> for i in range(len(table)):
...     print(table[i].get("name"))
...
admin
guest
lyshark

◆ tuple type

Tuple is a common data structure in Python. Tuple is composed of different elements. Each element can store different types of data, such as string, number or even tuple. Tuple is write protected, that is, after tuple is created, no modification can be done. Tuple usually represents a row of data, while elements in tuple represent different data items. Once tuple is created, it cannot be modified It is also called read-only list. Tuples use parentheses. Lists use square brackets. Tuples are easy to create. You only need to add elements in brackets and separate them with commas

Create tuples: see how tuples are created in the same instance

>>> tup1 = ("google","baidu",1997,1998)
>>> tup2 = (1,2,3,4,5,6,7)
>>> tup3 = "a","b","c","d"
>>>
>>> tup1
('google', 'baidu', 1997, 1998)
>>> tup2
(1, 2, 3, 4, 5, 6, 7)
>>> tup3
('a', 'b', 'c', 'd')
>>>
>>> type(tup1)
<class 'tuple'>

Access tuple: a tuple can use a subscript index to access the value in the tuple

>>> tup1
('google', 'baidu', 1997, 1998)
>>>
>>> print("tup1[0:]",tup1[0])
tup1[0:] google
>>> print("tup1[1:2]",tup1[1:2])
tup1[1:2] ('baidu',)

Join tuple: element value in tuple is not allowed to be modified, but we can join tuple

>>> tup1 = (1,2,3,4)
>>> tup2 = ("abc","xyz")
>>>
>>> tup3 = tup1+tup2
>>> print(tup3)
(1, 2, 3, 4, 'abc', 'xyz')

Delete tuple: the element value in tuple is not allowed to be deleted, but we can use del statement to delete the whole tuple

>>> tup = ("admin","lyshark", 1997, 2000)
>>>
>>> print(tup)
('admin', 'lyshark', 1997, 2000)
>>> del tup;
>>> print(tup)

List to tuple: converts a list to a primitive

>>> list = ["admin","lyshark","guest"]
>>>
>>> tuple = tuple(list)
>>>
>>> tuple
('admin', 'lyshark', 'guest')

Data statistics: count () function is used to count other data in tuple

>>> tuple
('admin', 'lyshark', 'guest')
>>>
>>> tuple.count("lyshark")    #Count the occurrence of lyshark
1
>>> tuple.index("lyshark")    #Count the index location of lyshark
1

Element modification (extension): in the absence of nesting, tuples are immutable objects, but lists within tuples are mutable

>>> tup=("lyshark",[1,2,3,4,5])
>>> tup
('lyshark', [1, 2, 3, 4, 5])
>>>
>>> tup[1].pop()
5
>>> tup
('lyshark', [1, 2, 3, 4])

Tuple unpacking (expanding): separate two tuples and queries, and store them in two variables respectively

>>> tup1,tup2=((1,2,3),("a","b","c"))
>>> print(tup1)
(1, 2, 3)
>>>
>>> print(tup2)
('a', 'b', 'c')

◆ type of collection

A set is an unordered and unrepeatable data combination. A set is naturally de duplicated. When a list is turned into a set, it is automatically de duplicated. A set does not support index, element acquisition, and slicing. There is no specific syntax format. You can only create a set through a factory function, but directly create a string. The elements in a set set must be iterative objects, and all elements will not be duplicated, unlike a list list It can be repeated

set.add(item)                       #Add an item to the set. If the item is already in the set, it has no effect
set.remove(item)                    #Delete item from set. If item is not a member of set, KeyError exception will be thrown
set.discard(item)                   #Delete item from set. If item is not a member of set, it has no effect
set.pop()                           #Randomly delete a set element and delete it from the set. If a variable is received, the deleted element will be received
set.clear()                         #Delete all elements in set
set.copy()                          #Shallow copy
set.update(t)                       #Add all elements in t to set, t can be another set, a sequence

set.union(t)                        #Union, return all elements in set and t
set.intersection(t)                 #Find intersection, return all elements in both set and t
set.intersection_update(t)          #Calculate the intersection of set and t, and put the result in set
set.difference(t)                   #Subtraction set, return all elements in set but not in t
set.difference_update(t)            #Remove all elements from the set that are also in t
set.symmetric_difference(t)         #Find the symmetric difference set, and return the set composed of all elements in the set without T and elements in the set without t
set.sysmmetric_difference_update(t) #Calculate the symmetric difference set between set and t, and put the result into set

set.isdisjoint(t)                   #Returns True if set and t do not have the same entry
set.issubset(t)                     #Returns True if s is a subset of t
set.issuperset(t)                   #Returns True if s is a superset of t

Create a collection: create a collection element in two ways

>>> s = {"tom","cat","name","lyshark"}
>>> s = set({"tom","cat","name","lyshark"})
>>>
>>> s
{'tom', 'cat', 'name', 'lyshark'}
>>> type(s)
<class 'set'>

Define variable set: define a variable set. The elements in the set are different

>>> set_test = set("hello")
>>> set_test
{'o', 'e', 'l', 'h'}

Define immutable set: define an immutable set. The elements in the set are different

>>> set_test = set("hello")
>>> set_test
{'o', 'e', 'l', 'h'}
>>>
>>> no_set_test = frozenset(set_test)
>>> no_set_test
frozenset({'o', 'e', 'l', 'h'})

Subsets: subsets are part of a set, so they are also called partial sets

>>> A = set('abcd')
>>> B = set("cdef")
>>> C = set("ab")
>>>
>>> C<A           #C is A subset of A
True
>>> C.issubset(A) #C is A subset of A
True
>>> C<B           #C is not a subset of B
False

Union: the union of a set is a set of all the elements of the set, excluding other elements

>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A | B
{'f', 'b', 'c', 'a', 'e', 'd'}
>>> A.union(B)
{'f', 'b', 'c', 'a', 'e', 'd'}

Intersection: the intersection of two sets A and B is A set that contains all elements that belong to both A and B, but no other elements

>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A & B
{'c', 'd'}
>>> A.intersection(B)
{'c', 'd'}

Difference set: the difference set of A and B is A set of all elements belonging to A and not belonging to B

>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A - B
{'a', 'b'}
>>> A.difference(B)
{'a', 'b'}

Symmetry difference: the symmetry difference of two sets is a set composed of elements that belong to only one set but not the other

>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A ^ B
{'f', 'b', 'a', 'e'}
>>> A.symmetric_difference(B)
{'f', 'b', 'a', 'e'}

Add element: use the add() function to add an element to an existing collection

>>> s = {1,2,3,4,5,6}
>>> s
{1, 2, 3, 4, 5, 6}
>>> s.add("s")
>>> s.add("e")
>>> s.add("t")
>>>
>>> s
{1, 2, 3, 4, 5, 6, 't', 's', 'e'}

Empty set: use the clear() function to empty all elements in a set

>>> s
{1, 2, 3, 4, 5, 6, 't', 's', 'e'}
>>>
>>> s.clear()
>>>
>>> s
set()

Delete the specified element: use the remove,discard function to delete the specified element in the collection

>>> s = {1,2,3,4,5}
>>> s
{1, 2, 3, 4, 5}
>>>
>>> s.remove(3)
>>> s
{1, 2, 4, 5}

Batch update element: use the update() function to update this collection with its own union with another

>>> s ={"p","y"}
>>> s
{'p', 'y'}
>>>
>>> s.update(["H","e"],{"1","2","3"})
>>> s
{'H', '1', 'y', 'p', '2', 'e', '3'}

Expand knowledge (1): find differences in multiple data

# Database has
old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}
# Data newly reported by cmdb
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
}
old_set=set(old_dict)
new_set=set(new_dict)
 
del_set=old_set.difference(new_set)
add_set=new_set.difference(old_set)
flush_set=old_set.intersection(new_set)
 
for i in del_set:
    old_dict.pop(i)
 
for i in add_set:
    old_dict[i]=new_dict[i]
 
for i in flush_set:
    old_dict[i] = new_dict[i]
print(old_dict)

Expand knowledge (2): find differences in multiple data

# Database has
old_dict = {
    "#1":8,
    "#2":4,
    "#3":2,
}

# Data newly reported by cmdb
new_dict = {
    "#1":4,
    "#3":4,
    "#4":2,
}


old_set = set(old_dict.keys())
print(old_set)
new_set = set(new_dict.keys())
print(new_set)

remove_set = old_set.difference(new_set)
print(remove_set)

add_set = new_set.difference(old_set)
print(add_set)

update_set = old_set.intersection(new_set)
print(update_set)

◆ sequence supplement

Sequence type refers to an ordered set of objects indexed to nonnegative integers, including strings, lists, tuples, strings that are character based, lists and tuples that are sequences of any python object, characters and tuples that are immutable, and lists that support inserting, deleting, and replacing elements. All sequences support iteration, of course tuples are immutable objects, and element operations are not supported, Of course, there are nested list dictionaries that can be operated. Here are some common sequence operation functions:

s + r               #Connection string, with data
s * n               #n replicates of s
v1,v2...vn = s      #Variable unpack
s[i]                #Indexes
s[i:j]              #Section
s[i:j:stride]       #Extended slice
x in s,x not in s   #Member relationship
for x in s:         #iteration
all(s)              #Returns True if all items in s are True
any(s)              #Returns True if any item in s is True
len(s)              #Length, number of elements
min(s)              #The smallest term in s
max(s)              #The largest term in s
sum(s [,initial])   #Sum of items with optional initializers

All judgment: returns True if all items in temp are True

>>> temp = [1,1,1,1,1,1]
>>> temp1 = [1,1,1,1,0,1]
>>>
>>> all(temp)
True
>>> all(temp1)
False

Any judgment: returns True if any item in temp is True

>>> temp = [1,1,1,1,1,1]
>>> temp1 = [1,1,1,1,0,1]
>>>
>>> any(temp)
True
>>> any(temp1)
True

len count elements: count related elements such as lists or dictionaries

>>> temp = [1,1,1,1,1,1]
>>> len(temp)
6

min returns min: returns the smallest value in the list

>>> temp = [1,2,3,4,5,6,7,8,9]
>>>
>>> min(temp)
1

max return maximum: returns the maximum value in the list

>>> temp = [1,2,3,4,5,6,7,8,9]
>>>
>>> max(temp)
9

◆ operation of documents

Open: the open function is used to open a file and return a handle

>>> f=open("./test.txt","r")
>>>

popen: use popen to store command execution results and print them

>>> temp=os.popen("ifconfig").readlines()
>>> temp
['eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500\n']

read: this function reads all the contents of the file at once

>>> f=open("./test.txt","r")
>>> f.read()

readline: this function reads one row of data at a time until all are read

>>> f=open("./test.txt","r")
>>> f.readline()
'root:x:0:0:root:/root:/bin/bash\n'
>>> f.readline()
'bin:x:1:1:bin:/bin:/sbin/nologin\n'
>>> f.readline()
'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'

Readlines: use readlines to read all content at once, which is equivalent to loading all

>>> f=open("./test.txt","r")
>>> f.readlines()

Seek: use seek to move the cursor position, and tell to get the current cursor position

>>> f=open("./test.txt","r")
>>> f.tell()                          #Query the current cursor position
0
>>> f.readline()                      #After reading a row
'root:x:0:0:root:/root:/bin/bash\n'
>>> 
>>> f.tell()                          #Query the cursor position again
32
>>> 
>>> f.read()                          #After full reading, the cursor is at the back of the file
'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
>>>
>>> f.seek(32)                        #Move cursor to 32
>>> 
>>> f.read()                          #Reread data
'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n'

flush: forces the data in memory to be flushed and written to disk

>>> import sys
>>> import time
>>> 
>>> for i in range(40):
...     sys.stdout.write("#")
...     sys.stdout.flush()         #Force data in memory to be written to hard disk
...     time.sleep(0.1)

Close: use close to close the file handle. Remember to close every time the open file is used up

>>> f=open("./test.txt","r")
>>> f.readlines()
>>> f.close()

Next: read one row of data at a time, and use the next function to load the next row

>>> f = open("./test.txt", "r")
>>> print ("File name is: ", f.name)

>>> for index in range(5):
...     line = next(f)
...     print ("The first %d That's ok - %s" % (index,line))

>>> f.close()

truncate: intercepts data. You can specify the number of bytes to be intercepted each time

>>> f = open("./test.txt", "r+")
>>> print ("File name is: ", f.name)

>>> f.truncate(10)           #Intercept 10 bytes
>>> str = f.read()
>>> print ("Read data: %s" % (str))
>>> f.close()

with: automatically open the file and release the file handle after execution

>>> with open('test.txt') as f:
...     print(f.read())

Linecache: open a file by using the linecache module, and calculate the total number of files

import sys
import linecache

count = len(open("./ip.log","r").readlines())
print("File rows(Including spaces): %d" %count)

count = linecache.getlines("./ip.log")
print("File rows(Support for large files): %d" %len(count))


Python process control

◆ while cycle

Branch structure:

# -*- coding: utf-8 -*-
import sys

number = 38
user_input = int(input("Enter a number:"))
if user_input == number:
    print("Bingo!")
elif user_input < number:
    print("Guess it's small.!")
else:
    print("Guess big.!")

To implement the addition cycle:

import sys

count = 1
sum = 0
while count <=100:
    sum+=count
    count+=1
print(sum)

Interrupt loop: demonstrates when a while loop is interrupted

import os

count = 0
while count <=9:
    print(count, end=' ')
    if count == 5:
        break
    count += 1
else:
    print('end')

Print string: print the specified string, print every element in it, and decrease every time

import sys

string = "hello lyshark"
while string:
    print(string)
    string = string[:-1]
else:
    print("gae over")

List printing: display all the elements in the specified list one by one. Here are three methods

>>> list=[1,2,3,4,5,6]
>>> count =0
>>>
>>> while list:
...     print(list[0])
...     list.pop(0)
...
>>> list=[1,2,3,4,5,6]
>>> while list:
...     print(list[-1])
...     list.pop()
...
>>> list=[1,2,3,4,5,6]
>>> while count < len(list):
...     print(list[count])
...     count+=1

Exercise example: find the sum of all even numbers within 100, and use nested judgment

>>> num=0
>>> sum=0
>>> while num <=100:
...     if num %2 ==0:
...             sum=sum+num
...     else:
...             pass
...  num=num+1

Exercise example: display all keys of the specified dictionary one by one, and state the total number of keys after the display

>>> d1 = {'x':1,'y':23,'z':78}
>>> keylists = d1.keys()
>>> while keylists:
        print(keylists[0])
        keylists.pop[0]
    else:
        print(len(d1))

Exercise example: create a list of all odd numbers within 100

>>> l1 = []
>>> x = 1
>>> while x < 100:
        l1.append(x)
        x += 2

Practice example: there are two lists L1 and L2 as follows. Take the element in the first list as the key and the element in the second list as the value to generate a new dictionary d1

>>> l1 = [0,1,2,3,4,5,6]
>>> l2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> d1 = {}
>>> count = 0
>>> if len(l1) == len(l2):
    while count < len(l1):
        d1[l1[count]] = l2[count]
        count += 1

>>> print(d1)

Exercise example: loop and print the relevant text, and exit when it reaches 100 times

count = 0
while True:
    print("hello lyshark:",count)
    count +=1
    if count == 100:
        print("break")
        break

Practice example: simulate the login applet. The password is required for program startup, and judge whether the login is successful if the number is less than 3 times. Otherwise, login is forbidden

import getpass
import os

name = "lyshark"
pwd = "123123"
count = 0

while True:
    if count < 3:
        print("Please enter user name and password:")
        username = input("User name:")
        password = getpass.getpass("Password:")

        if username == name and password == pwd:
            print("Congratulations on your landing!")
            break
        else:
            print("Login failed! Wrong user name or password")
    else:
        print("You've lost three times,Exit....")
        break

    count += 1

◆ for circulation

List traversal: print elements in a list by using the for loop

import os

names = ["tom","admin","lyshark","jack"]
for x in names:
    print(x)

List iteration: for a sequence, it can also be iterated by index

import os

names = ["tom","admin","lyshark","jack"]
for x in range(len(names)):
    print(names[x])

Print sequence: through for loop, traverse and print a sequence

import os

T = [(1,2),(3,4),(5,6),(7,8)]
for (a,b) in T:
    print(a,b)

Loop traversal: traverses all numbers in the range of 0-9, and prints out the odd numbers through the loop control statement

import os

for i in range(10):
    if i % 2 == 0:
        continue
    print(i, end=' ')

Loop traversal: print the first three elements of a list through loop control statements

import os

names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly']
for i in range(len(names)):
    if i >= 3:
        break
    print(names[i])

Loop traversal: print 99 multiplication table through for loop

import os

for j in range(1, 10):
    for i in range(1, j+1):
        print('%d*%d=%d' % (i, j, i*j), end='\t')
        i += 1
    print()
    j += 1

Loop traversal: through the range function, we can also achieve traversal

>>> string="hello world my name lyshark"
>>> for i in range(0,len(string),2):
...     print(string[i])

>>> list=[1,2,3,4,5]
>>> for i in range(len(list)):
...     list[i]+=1
>>> list
[2, 3, 4, 5, 6]

>>> for i in range(1,10,2):
    print(i)

enumrate: add a sequence number to an iterative object. By default, the number starts from 0. You can set it to start from 1

>>> list=["Sora Aoi","Xiao zemaria","Yoshizawa Akiho"]
>>> for (x,y) in enumerate(list,1):
    print(x,y)

1 Sora Aoi
2 Xiao zemaria
3 Yoshizawa Akiho

zip() function: the zip function is often used to construct a dynamic dictionary

>>> L1 = [1,2,3,4,5]
>>> L2 = ['a','b','c','d','e',]
>>> zip(L1,L2)
>>> 
>>> keys = [1,2,3,4,5,6,7]
>>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> D = {}
>>> for (k,v) in zip(keys,values)
       D[k] = v
>>> D

◆ other examples

Exercise example: display all elements in the specified dictionary d1 separately, that is, dictionary traversal printing

>>> d1 = {'x':123,'y':321,'z':734}
>>> for (k,v) in d1.items():
    print(k,v)
    
y 321
x 123
z 734

Exercise example: display the odd index elements of l1 in the list one by one

>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> 
>>> for i in range(1,len(l1),2):
    print(l1[i])

Exercise example: define all elements belonging to list l1 but not belonging to list l2 as a new list l3 and add them to it

>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] 
>>> l2=['Sun','Mon','Tue','Thu','Sat']
>>> l3 = []
>>> for i in l1:
>>>     if i not in l2:
>>>         l3.append(i)

Exercise example: please remove each element belonging to the removelist list from the namelist (it belongs to removelist, but not to the neglect of namelist)

>>> namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7']
>>> removelist=['stu3','stu7','stu9']
>>> for i in removelist:
>>>     if i in namelist:
>>>         namelist.remove(i)
>>> print(namelist)

Practice example: there are four numbers: 1, 2, 3, and 4. How many different and unrepeated three digit numbers can be composed? How many are each?

Program analysis: the numbers that can be filled in hundreds, tens and ones are all 1, 2, 3 and 4. After all the permutations are formed, the unqualified permutations are removed

>>> for i in range(1,5):
...     for j in range(1,5):
...             for k in range(1,5):
...                     if(i!=k) and (i!=j) and(j!=k):
...                             print(i,j,k)
...

Practice example: input a certain day of a certain year, and the program automatically judges the day as the day of the year?

Program analysis: take October 1 as an example, we should first add up the first nine months, and then add one day, which is the day of the year. In special cases, when the leap year and the input month is greater than 2, we need to consider adding one more day

# -*- coding: UTF-8 -*-
 
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
 
months = (0,31,59,90,120,151,181,212,243,273,304,334)

if 0 < month <= 12:
    sum = months[month - 1]
else:
    print ('data error')
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print ('it is the %dth day.' % sum)

Exercise example: output 9 * 9 multiplication formula table, consider lines and columns, 9 lines and 9 columns in total, i control line, j control column

import os
import sys

for x in range(1,10):
        print()
        for y in range(1,x+1):
                print("%d*%d=%d "%(y,x,x*y),end="")

Example: write a string traversal search tool, the code is as follows

import os
import sys

ls="Type help() for interactive help, or help(object) for help about object"

find="help"

for x in range(len(ls)):
        temp=len(find)
        if str(ls[x:x+temp]) == str(find):
                print(ls[x:x+temp],x)
                break

Exercise example: by using the sleep function in the time module, let the program execute a loop every 1 second

import os
import time

dic={1:"admin",2:"guest"}

for key,value in dict.items(dic):
        print(key,value)
        time.sleep(1)

Example: input a line of characters and count the number of English letters, spaces, numbers and other characters

import os
import string

strs=input("Please enter a string:")

letters=0
space=0
digit=0
others=0

for x in range(len(strs)):
        ch=strs[x]
        if ch.isalpha():
                letters+=1
        elif ch.isspace():
                space+=1
        elif ch.isdigit():
                digit+=1
        else:
                others+=1

print("char=%d,space=%d,digit=%d,others=%d"%(letters,space,digit,others))

Exercise example: read the db configuration file, and judge whether login is allowed according to the account password in the file

import os
import sys

def login(x,y):
    fp=open("db","r",encoding="utf-8")
    data=fp.readline().split(":")
    count=len(open("db","r").readlines())

    username=data[0]
    password=data[1]
    for i in range(3):
        if x==username.strip() and y==password.strip():
            print("Landing successfully")
            break
        else:
            data=fp.readline().split(":")
            username=data[0]
            password=data[1]
            continue
    fp.close()

login("admin","admin")
login("lyshark","lyshark")

Implementation element classification: there is the following value set list, which saves all values greater than 66 to the first key of the dictionary, and saves values less than 66 to the values of the second key, namely {'k1': all values greater than 66, 'k2': all values less than 66}

list= [11,22,33,44,55,66,77,88,99]
bignum=[]
smallnum=[]
dir={}
for num in list:
    if num>66:
        bignum.append(num)
    if num<66:
        smallnum.append(num)
    else:
        pass
dir['k1']=bignum
dir['k2']=smallnum
print(dir)

Implement element lookup: find elements, move spaces, and find all elements that start with a or a and end with c

li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
for i in li:
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print(i)
for i in tu:
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print(i)
for i in dic.values():
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print (i)

Realize commodity output: output commodity list, user input serial number, display commodity selected by user

#Method 1
l1=[1,2,3,4]
l2=["Mobile phone", "Computer", 'Mouse pad', 'Yacht']
d=dict(zip(l1,l2))
print(d)
num=input("Please enter the product number:")
print("The product you selected is %s" %d[int(num)])
 
#Method two
li = ["Mobile phone", "Computer", 'Mouse pad', 'Yacht']
for k, i in enumerate(li):
    print(k,i)
k=input("Please enter the product number:")
print("The product you selected is %s" % li[int(k)])

Guessing game: it allows users to guess the age continuously, but only gives 3 chances at most, and quit the program if the guessing is wrong

# -*- coding:utf-8 -*-

age = 22
count = 0

for i in range(10):
    if count < 3:
        a = int(input("Please enter a guess:"))
        if a == age:
            print("Congratulations,Bingo")
            break
        elif a > age:
            print("You've got a big number")
        else:
            print("Your guess is small")
    else:
        b = input("That's not right,Do you keep playing?(yes or not):")
        if b == 'yes':
            count = 0
            continue
        else:
            print("Bye!Play again next time.")

    count += 1

Realize three - level menu: realize user interaction, display the three - level linkage selection of province, city and county

dic = {
    "Hebei": {
        "Shijiazhuang": ["Luquan", "Gaocheng", "Yuanshi"],
        "Handan": ["throughout the year", "Shexian County", "Cixian"],
    },
    "Hunan": {
        "Changsha":['a','b','c'],
        "Zhuzhou":['d','e','f']
    },
    "Hubei": {
        "Wuhan":['g','h','i'],
        "Huangshi":['j','k','l']
    }
}
for k in dic.keys():
    print(k)
flag=True
while flag:
    n=input("Please enter your province:")
    for k in dic.keys():
        if n in dic.keys():
            if k == n:
                for i in dic[n].keys():
                    print(i)
                w = input("Please enter your city:")
                for i in dic[n].keys():
                    if w in dic[n].keys():
                        if i == w:
                            for k in dic[n][w]:
                                print(k)
                            s=input("Please enter your county:")
                            for j in dic[n][w]:
                                if s in dic[n][w]:
                                    if j==s:
                                        print("Your location is:%s province%s city%s county" % (n,w,s))
                                        flag = False
                                        break
                                else:
                                    print('No, please re-enter')
                                    break
                    else:
                        print('No, please re-enter')
                        break
        else:
            print('No, please re-enter')
            break

Implement a shopping cart: implement a shopping cart applet, and meet the following requirements

product = [
    ("iphone",5800),
    ("watch",380),
    ("bike",800),
    ("book",120),
    ("computer",4000)
]
 
shopping_car = []
 
salary = input("Please input your money: ")
if salary.isdigit():
    salary = int(salary)
    while True:
        for i in enumerate(product):
            print(i)
 
        user_choice = input(">>>perhaps q:")
 
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice >= 0 and user_choice < len(product):
                p_item = product[user_choice]
                if salary >= p_item[1]:
                    shopping_car.append(p_item[0])
                    salary -= p_item[1]
                    print("You bought it.\033[32m%s\033[0m,Your balance is surplus\033[31m%s\033[0m" % (p_item[0], salary))
                else:
                    print("\033[31m Your balance is insufficient\033[0m")
            else:
                print("Items you entered[%s]Non-existent,Please re-enter" % user_choice)
        elif user_choice == 'q':
            print("You bought these goods:".center(30,"-"))
            for i in shopping_car:
                print("\033[32m%s\033[0m" %i)
            print("\033[31m balance%s\033[0m" %salary)
            exit()
        else:
            print("What you entered[%s]Non-existent" % user_choice)
else:
    print("The amount you entered is incorrect! Please re-enter the amount!")


Python advanced features

◆ Python iterator

Iterators are a way to access collection elements. Iterator objects are accessed from the first element of the collection until all elements are accessed. Iterators can only move forward and not backward. Iterators are especially suitable for traversing some huge or infinite collections, such as files with a size of GB level, which is particularly efficient

Create a basic iterator: first declare a list, then use 'iterator' to turn it into an iterator, and iterate over the iterated object through 'next'

>>> list = [1,2,3,4,5,6,7,8,9,10]
>>>
>>> item = list.__iter__()
>>> type(item)
<class 'list_iterator'>
>>>
>>> item.__next__()
1
>>> item.__next__()
2
>>> next(item)
3
>>> next(item)
4

Iterator and tuple conversion: by using the enumerate method, the list is converted to an iterator and then forced to a tuple

>>> listvar = ["Lu Dong Bin", "Zhang Guo Lao", "LAN Tsai", "Special obedient", "Letinous edodes", "Han Zhong Li", "Wang Wen"]
>>>
>>> iter = enumerate(listvar)  # Convert to iterator
>>> dict = tuple(iter)         # Convert to tuple
>>> print(dict)
((0, 'Lu Dong Bin'), (1, 'Zhang Guo Lao'), (2, 'LAN Tsai'), (3, 'Special obedient'), (4, 'Letinous edodes'), (5, 'Han Zhong Li'), (6, 'Wang Wen'))

Loop traversal iteration element: because the iterator will report an error at the end of traversal, the try statement is used to throw an exception

>>> listvar = ["Lu Dong Bin", "Zhang Guo Lao", "LAN Tsai", "Special obedient", "Letinous edodes", "Han Zhong Li", "Wang Wen"]
>>> item = listvar.__iter__()
>>>
>>> while True:
...     try:
...             temp = next(item)
...             print(temp)
...     except StopIteration:
...             break

◆ Python generator

Generator is a special program, which can be used to control the iterative behavior of loops. In Python, generator is a kind of iterator. Using yield return value function, yield will pause every time you call it, and next() function and send() function can be used to restore the generator

When we call a generator function, we actually return an iterator object
In Python, as long as the expression is used, yield function is usually called generator
When you run the generator, each time you encounter a yield function, it automatically saves and pauses execution until you use the next() method to continue the iteration
Unlike ordinary functions, a generator is a function that returns an iterator, which can only be used for iterative operations. More simply, understand that a generator is an iterator

Before learning the generator, we need some pre knowledge. First, we need to study list parsing. List parsing is an application of Python iteration mechanism. It is often used to create new lists. Therefore, to be placed in [], list parsing is very flexible. Users can quickly create a set of list elements of corresponding rules and support iterative operation

Factoring: realize the iterative factoring of list through list analytic expression

>>> temp1 = [1,2,3,4,5]
>>> temp2 = [ x ** 2 for x in temp1 ]

>>> temp1
[1, 2, 3, 4, 5]
>>> temp2
[1, 4, 9, 16, 25]

Factoring: through list parsing, iterative factoring is realized, and only data larger than 2 (if x > = 2) is printed

>>> temp1 = [1,2,3,4,5]
>>> temp2 = [ x**2 for x in temp if x>=2 ]

>>> temp1
[1, 2, 3, 4, 5]
>>> temp2
[4, 9, 16, 25]

Factorization: through the list analytical formula, the iterative factorization is realized, and the relevant data is generated through the range function

>>> temp = [ (x**2)/2 for x in range(1,10)]
>>> temp
[0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5]

Data merging: through list parsing, the two lists are merged according to rules

>>> temp1=["x","y","z"]
>>> temp2=[1,2,3]
>>> temp3=[ (i,j) for i in temp1 for j in temp2 ]
>>> temp3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

File filtering: through the use of list parsing, to achieve text filtering operations

>>> import os

>>> file_list=os.listdir("/var/log")
>>> file_log=[ i for i in file_list if i.endswith(".log") ]
>>> print(file_log)
['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log']

>>> file_log=[ i for i in os.listdir("/var/log") if i.endswith(".log") ]
>>> print(file_log)
['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log']

Next, let's study the generator. The generator is similar to a function whose return value is an array. This function can accept parameters and can be called, but different from the general function, it will return an array containing all values at once. The generator can only produce one value at a time, so the amount of memory consumed will be greatly reduced, and the calling function is allowed to process quickly Several return values, so the generator looks like a function, but behaves like an iterator

Let's first look at the comparison between the following two situations. The first method is very simple. Only by changing the [] bracket of a list generation type to () bracket, a generator is created

>>> lis = [x*x for x in range(10)]
>>> print(lis)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> generator = (x*x for x in range(10))
>>> print(generator)
<generator object <genexpr> at 0x0000022E5C788A98>

As an example above, the first lis creates a list through list generation, while the second generator prints out a memory address. If we want to get the data in the second variable, we need to iterate as follows:

>>> generator = (x*x for x in range(10))

>>> print(next(generator))
0
>>> print(next(generator))
1
>>> print(next(generator))
4
>>> print(next(generator))
9

As you can see above, the generator saves the algorithm. Every time it calls next (generatotr), it calculates the value of its next element until it calculates the last element. Using for loop can easily traverse the data in the iterator, because the generator is also an object that can be iterated

>>> generator = (x*x for x in range(10))
>>> 
>>> for i in generator:
    print(i,end="")

0149162536496481

The generator expression does not really create a list of numbers, but returns a generator object. This object "yields" this item every time it calculates an item. The generator expression uses "lazy calculation" or a mechanism sequence called "delayed evaluation" which is too long. When only one element needs to be obtained each time, we should consider using the generator expression instead of list parsing

>>> import sys
>>> 
>>> yie=( i**2 for i in range(1,10) )
>>> next(yie)
1
>>> next(yie)
4
>>> next(yie)
9

>>> for j in ( i**2 for i in range(1,10)):print(j/2)

Practice examples: generate several generators through functions, and yield keywords

>>> import sys
>>> 
>>> def func():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5

>>> temp=func()
>>> temp.__next__()
1
>>> temp.__next__()
2
>>> temp.__next__()
3

Exercise example: use while loop to build a generator and print the result through for traversal

>>> import sys
>>> 
>>> def yieldNum(x):
    y=0
    while (y <= x):
        yield y
        y += 1
    
>>> yie=yieldNum(5)
>>> for i in yie:
    print(i)

Exercise example: use the generator to square 1 - 10

>>> def yieldNum():
    x=1
    while (x <=10 ):
        yield x ** 2
        x += 1

>>> yie=yieldNum()
>>> 
>>> for i in yie:
    print(i)

Exercise example: use generator to implement range function

>>> def xrange(num):
    temp=-1
    while True:
        temp=temp+1
        if (temp >= num):
            return
        else:
            yield temp

>>> xrange(10)
<generator object xrange at 0x038E3030>

Example: find Fibonacci series by using generator

>>> def fib(max):
    n,a,b=0,0,1
    while n < max:
        yield b
        a,b=b,a+b
        n+=1
    return "done"

>>> f=fib(5)
>>> f
<generator object fib at 0x038F4A20>

Exercise example: use generator to achieve concurrent effect in the case of a single process

import time
def consumer(name):
    print("%s Ready to eat steamed buns!" %name)
    while True:
       baozi = yield
 
       print("Steamed stuffed bun[%s]Coming,cover[%s]Ate!" %(baozi,name))
 
def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("I'm getting ready to make steamed buns!")
    for i in range(10):
        time.sleep(1)
        print("Made two buns!")
        c.send(i)
        c2.send(i)
 
producer("alex")

Tags: Python pip Ruby yum

Posted on Tue, 14 Jan 2020 04:53:32 -0500 by mattchewone