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']
- Addition, deletion, modification and query of list
- Visit: english[0]
- Modify english[0] = 'd'
- Add english.insert(0, 'e') to insert to the specified location
- english.append('f ') append
- Delete english.pop() and pop up the last one
- english.pop(0) pops up the first element
- english.remove('a ') delete the specified element, delete the first
- del english(0) delete the specified location
- Organization list
- sort() permanent sort is sorted alphabetically by default
- sort(reverse=True) sort by subtitle in reverse order
- sort() is to sort the object address directly, and it is permanent after sorting
- sort() and sort() are basically the same, but the temporary sorting does not affect the objects in the address
- sorted([1,3,2])
- [1,3,2].sort()
- reverse() reverse data list
- len(english) output list length
- Operation list
- for cycle
- english = ['a','b','c','d']
-
for e in english: print(e)
- range() value loop, before and after
for value in range(1,5): print(value)
- Create a list of numbers with range(): list(range(1,12,2)), create a list in steps of 2 from 1-11
- Statistics of number list, min(),max(),sum()
- A wonderful writing method: squares = [value**2 for value in range(1,11)]
- for loop provides value to value, and then value**2 calculates the square and stores it in the list
- for cycle
- List slice
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
- Different from java, strings in python can be directly compared with = = in java
if 1 == 1 : print('Yes') else : print('Wrong')
- Using elif
age = 12 if age < 4: print('your admission cost is 0') if age < 18: print('your admission cost is 5')
- Use & & and instead, or instead
- You can use not in and in to determine whether an element is in the list
Dictionaries
- dict = {'name':'json','length':30}
Similar to map, use dict ['name'] to access - You can also define dictionary variables before adding values
dict = {} dict['name']='json' dict['length']=30;
- Modify also directly according to the key dict ['name'] = 'xml'
- Delete the key value pair del dict in the dictionary ['length']
- 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)
- dict.keys() gets all the keys in the dictionary, dict.values() gets all the values
- Use set() to de duplicate, set(dict.values)
- If duplicate keys are used in the dictionary, the last key will be overwritten
input() and while() loops
input() function- name = input('Please input your name ') (the user's input will be the most name value
- input accepts strings
index = 1 while index <= 10: print(index) index++
- break exit loop
- 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 ')
- When using default parameters, parameters with default values must be written at the back
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 ····
- The modification of object point content by function is permanent
- Function changes to variables are temporary
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
- Import the whole module
import module_name ## Aliases, if any, must be used import module_name mn
- 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
- 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
- Every class related method will automatically pass self, which is a reference to an instance, this in java
- You do not need to pass the self argument manually when using the methods of a class
- Methods in a class are no different from other methods except for one self
Inheritance:
- The parent class and subclass must be in a file (import can be used to import them), such as from super class import superclass
- 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)
- Rewrite, just like java
Files and exceptions
with open('pi.txt') as file_object: contents = file_object.read() print(contents.rstrip())
- 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
- You must close the file after using it, otherwise it will cause unpredictable errors
- with is whether python automatically judges whether the file has been used and then automatically closes it
- read(), read out the file
- 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)
- strip() removes the empty string from the string
- String is a list of characters. You can use str_value[:55] to get the first 55 bits
- 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)
- 'w' in open() indicates the write mode, which is' r 'by default
- 'r' read mode
- 'w' write mode
- 'a' additional mode
- 'r +' read write mode
- 'rb' binary read, 'wb' binary write
- 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
- write() writes the contents to the file object
- Python can only write strings to files. To store values, first use the str() function to convert them to string format
- 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)
- If there is no exception, the code block of else is executed
- pass does nothing
JSON
- Json.dump (data, file object)
- Json.load (file object)
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
- Install PyMySQL
- 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()
- Insert, update and delete are all operations to change the database, and the update operation must be a transaction
- affair
try: cursor.execute(sql) db.commit() except: db.rollback()
Store in MongoDB
- Install PyMongo
- Connect MongoDB
- Get connection client
import pymongo client = pymongo.MongoClient(host='localhost',port=27017) # Or client = MongoClient('mongodb://localhost:27017 / ')
- Specify database as test library
db = client.test # Or db = client['test ']
- Specify the collection as students
collection = db.students collection = db['students']
- MongoDB can be inserted directly by using the constructed dictionary type
student = { 'id':'1001', 'name':'Li Si' } result = collection.inset(student)Pineapple Published 57 original articles, won praise 6, visited 7247 Private letter follow