Python review notes

Start with python review

  • Simple data types and variable naming conventions are the same as others, starting from different lists

list

english = ['c','b','a']

  1. Addition, deletion, modification and query of list
    1. Visit: english[0]
    2. Modify english[0] = 'd'
    3. Add english.insert(0, 'e') to insert to the specified location
      1. english.append('f ') append
    4. Delete english.pop() and pop up the last one
      1. english.pop(0) pops up the first element
      2. english.remove('a ') delete the specified element, delete the first
      3. del english(0) delete the specified location
  1. Organization list
    1. sort() permanent sort is sorted alphabetically by default
    2. sort(reverse=True) sort by subtitle in reverse order
    3. sort() is to sort the object address directly, and it is permanent after sorting
    4. sort() and sort() are basically the same, but the temporary sorting does not affect the objects in the address
      1. sorted([1,3,2])
      2. [1,3,2].sort()
    5. reverse() reverse data list
    6. len(english) output list length
  1. Operation list
    1. for cycle
      1. english = ['a','b','c','d']
      2.  for e in english:
         	print(e)
        
    2. range() value loop, before and after
      	for value in range(1,5):
      		print(value)
      
    3. Create a list of numbers with range(): list(range(1,12,2)), create a list in steps of 2 from 1-11
    4. Statistics of number list, min(),max(),sum()
    5. A wonderful writing method: squares = [value**2 for value in range(1,11)]
      1. for loop provides value to value, and then value**2 calculates the square and stores it in the list
  2. List slice
english = ['a','b','c','d']
print(english[0:3]) output 0,1,2 contains before but not after
 You can also use english[:3] ා when the current one is 0, write directly to the following
 You can also english[2:] from index 2 to last
 You can even copy the current list in english [:], and store the original copy of the list under the new list address

tuple

  • Use parentheses to define
    tuple = ('a','c','d',['1','2','3'])
    Immutability, in which tuple and list are very similar, but tuple has more immutability than list, and the element is immutable, which means that the address pointed to by the element is immutable but the content in the address is variable:
    For example, tuple[0] = 'e', no
    tuple[3][0]='4' yes, because tuple[3][0] points to a list. The value of the list changes, but the address of the list is immutable

if

- in Python, False,0, ', [], {}, () can be treated as false

  1. Different from java, strings in python can be directly compared with = = in java
if 1 == 1 :
	print('Yes')
else : 
	print('Wrong')
  1. Using elif
age = 12
if age < 4:
	print('your admission cost is 0')
if age < 18:
	print('your admission cost is 5')
  1. Use & & and instead, or instead
  2. You can use not in and in to determine whether an element is in the list

Dictionaries

  1. dict = {'name':'json','length':30}
    Similar to map, use dict ['name'] to access
  2. You can also define dictionary variables before adding values
dict = {}
dict['name']='json'
dict['length']=30;
  1. Modify also directly according to the key dict ['name'] = 'xml'
  2. Delete the key value pair del dict in the dictionary ['length']
  3. Traverse the dictionary. The key of the dictionary is stored through hash, so it is unordered
dict = {'name':'json','length':30,'age':'12'}
for key,value in dict.items():
	print('key:'+key+'value'+value)
  1. dict.keys() gets all the keys in the dictionary, dict.values() gets all the values
  2. Use set() to de duplicate, set(dict.values)
  3. If duplicate keys are used in the dictionary, the last key will be overwritten

input() and while() loops

input() function

  1. name = input('Please input your name ') (the user's input will be the most name value
  2. input accepts strings

while

index = 1
while index <= 10:
	print(index)
	index++
  1. break exit loop
  2. continue skip this cycle
while 'a' in english:
	english.remove('a')

Summary: in python, while is similar to java, but the syntax format changes

function

## Define function, start with def, and put parameter name directly in parentheses
def greet_user(username):
	print("Hello, "+ username.title() + "!")

greet_user('Yunpeng.Gu')

Location arguments:

def describe_pet(animal_type,pet_name):
	···

Use position parameters in order

Keyword arguments:

def describe_pet(animal_type,pet_name):
	···

describe_pet(pet_name='harry',animal_type='hamster')
Pass arguments with parameter names

Default value:

def describe_pet(pet_name,animal_type="dog"):
	···

Describe? Pet (pet? Name = 'Harry') or describe? Pet ('harry ')

  1. When using default parameters, parameters with default values must be written at the back

Return value

Using return, you can return various types without declaring in advance

def get_formatted_name(first_name,last_name):
	## Return string
	full_name = first_name + " " + last_name
	return full_name.title()
	## Return dictionary
	full_name = {'first_name':first_name,'last_name':last_name}
	return full_name

	····
  1. The modification of object point content by function is permanent
  2. Function changes to variables are temporary

Variable parameters

def function_name(*value):
	···
*It's python that creates an empty tuple and encapsulates the received values into the tuple
 If there are other parameters at the same time, put the variable parameter last and there can only be one variable parameter

Variable key parameters:
Prefix with * *

def build_profile(first,last,**user_info):
	···
	profile={}
	for key,value in user_info.items():
		profile[key]=value

build_profile('gu','yunpeng',location='beijing',age=21,sex='man')

Modular

A py file is a module
Importing a module is a Python interpreter that opens the module file and copies the imported code

  1. Import the whole module
import module_name
## Aliases, if any, must be used
import module_name mn
  1. Import specific functions
from module_name import function_name 
## Aliases, if any, must be used
from module_name import function_name as fn
## Import multiple functions and alias them at one time
from module_name import function_name1 as fn1,function_name2 as fn2
  1. Import all functions in the module
from module_name import *
## If Python encounters a function with the same name, it will overwrite it, so this method is not generally used

class

def __init__(self,name,age):
	self.name = name
	self.age = age

init() method, constructor, must declare self and must run before other parameters when creating an instance of a class

  1. Every class related method will automatically pass self, which is a reference to an instance, this in java
  2. You do not need to pass the self argument manually when using the methods of a class
  3. Methods in a class are no different from other methods except for one self

Inheritance:

  1. The parent class and subclass must be in a file (import can be used to import them), such as from super class import superclass
  2. The parent class must be declared before the child class
class ClassName(SuperClass):
	def __init__(self,name,age,sex):
		## You do not need to pass in self when initializing the parent class
		super().__init__(name,age,sex)
  1. Rewrite, just like java

Files and exceptions

with open('pi.txt') as file_object:
	contents = file_object.read()
	print(contents.rstrip())
  1. open(), if you want to use the file, you must use open to open the file, return a file object, and use as to name the file object as "file" object
  2. You must close the file after using it, otherwise it will cause unpredictable errors
  3. with is whether python automatically judges whether the file has been used and then automatically closes it
  4. read(), read out the file
  5. rstrip() removes the blank string at the end of the string

Read by line

with open('pi.txt') as file_object:
	for line in file_object:
		print(line)
  1. strip() removes the empty string from the string
  2. String is a list of characters. You can use str_value[:55] to get the first 55 bits
  3. You can also use content in str value to determine whether content is included in str value

Writing file

with open(path_prefix+"file_write.txt",'w') as file_writer:
    name = input("Please Enter Your Name: ")
    file_writer.write(name)
  1. 'w' in open() indicates the write mode, which is' r 'by default
    1. 'r' read mode
    2. 'w' write mode
    3. 'a' additional mode
    4. 'r +' read write mode
    5. 'rb' binary read, 'wb' binary write
  2. If the file to be written does not exist Python will create it, if it does, it will be emptied before creating the file object
  3. write() writes the contents to the file object
  4. Python can only write strings to files. To store values, first use the str() function to convert them to string format
  5. If you want to wrap on write, add line wrap at the end of the string \ n

abnormal

try:
	answer = int(first_number) / int(second_number)
except ZeroDivisionError:
	print("You can't divide by 0!")
else:
	print(answer)
  1. If there is no exception, the code block of else is executed
  2. pass does nothing

JSON

  1. Json.dump (data, file object)
import json
numbers = [1,3,5,1,2]
with open(filename,'w') as file_obj:
	json.dump(numbers,f_obj)
	Write data to file as json
  1. Json.load (file object)
with open(filename,'r') as f_obj:
	json.load(f_obj)
	Parse the data as json type

Summary of Python: if Python has a chance to build numbers or crawlers in the future, after all, it is not so used to the third-party library of python, and the efficiency may not be high

csv

1. writing files
1.1 general write

	 with open('../config/data.csv', 'w') as csvfile:
     	writer = csv.writer(csvfile)
      	writer.writerow(['id', 'name', 'age']) #Writing header
		writer.writerow(['1001', 'Zhang San', '22']) #Writing content

1.2 specify separator

	with open('../config/data.csv', 'w') as csvfile:
		writer = csv.writer(csvfile,delimiter = '#')
		writer.writerow(['id', 'name', 'age']) #Writing header
		writer.writerow(['1001', 'Zhang San', '22']) #Writing content

1.3 write multiple lines at the same time

    with open('../config/data.csv', 'w') as csvfile:
        writer = csv.writer(csvfile,delimiter = '#')
        writer.writerows([['id', 'name', 'age'],['1001', 'Zhang San', '22'],['1001', 'Wang Wu', '23'],['1001', 'Li Si', '21']])

1.4 writing dictionary contents

    with open('data.csv','w') as csvfile:
        fieldnames = ['id','name','age'] #Designated header
        writer = csv.DictWriter(csvfile,fieldnames=fieldnames) #Configuration header
        writer.writeheader() #Write header to file
        writer.writerow({'id':'1001','name':'mike','age':'11'}) #Write contents

2 read files
2.1 parsing csv using pandas Library
df = pd.read_csv('../config/data.csv',encoding='gbk') print(df)

Store in mysql

  1. Install PyMySQL
  2. Test connection
    	import pymysql
    	# Connect to mysql
    	db = pymysql.connect(host='localhost',user='root',password='root',port=3306)
    	# Get cursor
    	cursor = db.cursor()
    	# Execute sql statement
    	cursor.execute('select 1 from dual')
    	# Close database connection
    	db.close()
    
  3. Insert, update and delete are all operations to change the database, and the update operation must be a transaction
    1. affair
    try:
    	cursor.execute(sql)
    	db.commit()
    except:
    	db.rollback()
    

Store in MongoDB

  1. Install PyMongo
  2. Connect MongoDB
    1. Get connection client
    import pymongo
    client = pymongo.MongoClient(host='localhost',port=27017)
    # Or client = MongoClient('mongodb://localhost:27017 / ')
    
    1. Specify database as test library
    db = client.test
    # Or db = client['test ']
    
    1. Specify the collection as students
    collection = db.students
    collection = db['students']
    
  3. MongoDB can be inserted directly by using the constructed dictionary type
student = {
	'id':'1001',
	'name':'Li Si'
}
result = collection.inset(student)
  1. More PyMongo API s
Published 57 original articles, won praise 6, visited 7247
Private letter follow

Tags: Python JSON Java MongoDB

Posted on Sun, 02 Feb 2020 04:40:18 -0500 by Rokboy