程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python study note

編輯:Python

Catalog

Comments and quotation marks are used 、 code

Data types and variables

lambda、zip、map、reduce、enumerate function

_xx、__xxx、__xxx__ The difference between

class 、 Function definition 、 exception handling

IO Programming

Comments and quotation marks are used 、 code

# encoding=utf-8 perhaps # -*- utf-8 -*-

Single-line comments :#

Multiline comment :''' ''' perhaps """ """

character string : Single quotation marks :'' Double quotes :" " Three quotes :''' ''' or """ """, Three quotes support line wrapping

escape :r'',r Do not escape string

Data types and variables

Integers (int)、 Floating point numbers (float)、 The plural (complex)、 character string (str)、 Boolean and null values

test_int = 1
test_float = 1.0
test_str = "abc"
test_complex = complex(1,2)
test_bool_1 = True
test_bool_2 = False
test_none = None

Tuples (tuple)、 list (list)、 Dictionaries (dict)、 aggregate (set)

# Tuples are immutable
test_tupble = (1,2,3)
test_list = [1,2,3]
test_dict = {"a":1,"b":2}
# Empty collection must use test_set = set(),test_set = {} Will resolve to an empty dictionary
test_set = {"a","b","c"} 

Correlation function description

'''
Array sorting :sorted
The length can be used :len()
String formatting :"{},{}".format("a","b")
Insert elements : The order of a (list):append
Non sequential concept (set):add
Class's own function (__xxx__ Format , It's usually a function , So when calling, it is usually __xxx__()):__len__()
'''
test_tuple = (1,2,3)
print(len(test_tuple))
print(test_tuple.__len__())

lambda、zip、map、reduce、enumerate function

from functools import reduce
test_list_1 = ['a','b','c']
test_list_2 = [1,2,3]
# zip
for index,value in zip(test_list_2,test_list_1):
print(index,value)
# enumerate
for index,value in enumerate(test_list_1):
print(index,value)
#reduce
test_reduce = reduce(lambda x,y:x+y,test_list_2)
print(test_reduce)
#lambda map
test_map = map(lambda x:x*2,test_list_2)

_xx、__xxx、__xxx__ The difference between

class TestClass():
'''
_xx:Python There is no real private method in . To achieve something similar to c++ Private methods in , You can add a before a method or property of a class “_” Underline , This means that the method or property should not be called , It doesn't belong to API.
__xx: It is not used to identify that a method or property is private , The real function is to avoid subclasses covering its contents . When compiled, it will become _A__method()
__XX__: be used for python call , Do not use
'''
def __init__(self):
self._test_a = 1
def __method(self):
print("This method from A!")
def method(self):
self.__method()

class 、 Function definition 、 exception handling

class TestClass():
def __init__(self):
self.test_x = 1
def test_exception(self):
try:
print("aaa")
raise ValueError("value error")
except ValueError as e:
print(e)
finally:
print("try except finally example!")
test_class = TestClass()
test_class.test_exception()

IO Programming

File read and write

file_name = "test.txt"
try:
f = open(file_name,"w+",encoding="utf-8")
for line in f.readlines():
print(line)
test_write = " Test write data "
f.write(test_write)
f.close()
except Exception as e:
print("exception:",e)
finally:
if f:
f.close()
try:
with open(file_name,"w+",encoding='utf-8') as f:
for line in f.readlines():
print(line)
except Exception as e:
print("exception:",e)

serialize :joblib and pickle

#joblib sklearn Self contained , More efficient ,joblib There is no function to sequence into strings
import joblib
import pickle
file_path = "xxxxx"
joblib.load(file_path)
joblib.dump(file_path)
#pickle
f = open("file_path",'rb')
d = pickle.load(f)
f.close()
# Store in file
f = open("file_path","wb")
pickle.dump(d,f)
f.close()
#dumps Serialize to string
d= dict(name="bob",age=20)
d_b = pickle.dumps(d)
#
d = pickle.loads(d_b)

os and sys modular

import os
import sys
# os Refers to operating system related , There is , For example, file path 、 Catalog
# sys Refers to system related , such as python Running path of , The path of the library
os.path.abspath(".")
sys.path.append("..")
sys.path

Common built-in modules


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved