關於數據結構:
列表 list: 定義的數據包括在 [] 中。列表中的數據是可修改的。例如
testlist = [1,2,3]. 或 testlist = list([1,2,3])
testlist[0] = 7
元組 tuple: 定義的數據包括在() 中,元組中的數據是不可修改的。當定義的元組只有一個數據時,數據後必須有一個逗號,如:(1, )。
testtuple = (1,2,3) 或 testtuple = tuple((1,2,3))
字典 dict: 字典中數據是以鍵值對的形式存在的,關於函數:d = {key1:value1, key2:value2}。定義及讀取方式
集合 set:是無值的字典。使用 {} 括起來。集合中不包含重複元素。定義空集合的時候,必須使用 set 函數進行創建。
a = {1,2,3,4,5} 或 a = set((1,2,3,5)) 集合只可以包含值不可變的元素。添加列表list,或字典時會報錯
集合和列表、字典可以通過解析函數(循環部分寫右邊,集合表達式寫在左邊)定義
{x for x in ‘spam’} = {‘s’,’p’,’a’,’m’}
[x for x in ‘spam’] = [‘s’,’p’,’a’,’m’]
{x:x*2 for x in range(2)} {0: 0, 1: 2}
list, tuple,set 這些函數中,參數可以是任何序列。需要拷貝時,
需要使用copy函數進行拷貝,
分片L[:] 可以拷貝。
有些內置函數如 list(L) 可以拷貝。
切片 L[1 : 10 : 3] 1表示起始位置。 10 表示結束位置, 3 表示步長。
文件中打包二進制數據的存儲與解析:
需要用到struct模塊。struct模塊能夠把文件中的字符串解讀爲二進制數據。
fmt 參數:
The optional first format char indicates byte order, size and alignment:
@: native order, size & alignment (default)
=: native order, std. size & alignment
<: little-endian, std. size & alignment
>: big-endian, std. size & alignment
!: same as >
pack(...)
pack(fmt, v1, v2, ...) -> bytes
unpack(...)
unpack(fmt, buffer) -> (v1, v2, ...)
Return a tuple containing values unpacked according to the format string
fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)
for more on format strings.
關於語法:
if 語句格式
if x == 'test':
print('test')
elif x == 'no':
print('no')
else:
print('default')
if / else 三元表達式
A = Y if X else Z
當 X 爲真, 執行 Y,
當X 爲假, 執行 Z。
while 循環
i = 10
while i > 0:
print("i = %d"%i)
i = i - 1
else:
print("End")
for 循環
for i in range(1,10):
for j in range(1,i+1):
print("%d * %d = %d"%(j,i,j*i), end = ' ')
print("")
else:
print("endfor")
output:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
endfor
循環中可以使用 break , continue, pass(什麼都不做。)
關於函數:
python 中函數參數可以使用* , **修飾。
def func(*name) *name 表示可變參數。參數爲一個序列(元組),跟在*後的任何正式或默認的參數名稱,都是keyword-only參數(帶關鍵字名字的參數)
def func(**name) **name 表示一個字典,對應有相應的key和value。此形式的參數必現放在參數列表最後。
def func(**name):
for item in name:
print("name[%s]"%(item), "=" ,name[item])
func(value=1,hell=2)
輸出結果爲:
name[value] = 1
name[hell] = 2
當前執行的文件的 __name__ 值爲 ‘__main__’
裝飾器decorator,是使用一個返回函數的函數放置在定義的函數前面。例如:
def log(func):
def wrapper(*arg, **kw):
print("Call %s"%func.__name__)
return func(*arg,**kw)
return wrapper
@log
def now():
print("Test log")
print(now.__name__)
輸出 wrapper
類似於 __xxx 這樣的函數或變量就是非公開的(private) 不能直接引用。__xx__ 此種變量名錶示是特殊變量,是可以直接訪問的,定義時避免使用此種類型的變量。
日誌打印
import logging
logging.basicConfig(level=logging.INFO) #設置日誌級別
logging.info(“打印日誌”)
匿名函數
lambda arg1, arg2,....argN : expression using arg
f = lambda x,y,z : x+y+z
f(2,3,4) = 9
關於類:
class ClassName(Objec1, Object2,...):
pass
ClassName 表示類名, Object表示繼承自某類。
__init__ 函數 初始化類中的變量等。此函數在創建類的實例時調用。類似於構造函數。
class Test:
testparam = 0
# __init__ 初始化函數。
def __init__(self):
self.one = 10
__slots__ 用來限制綁定的屬性名稱。使用此屬性約束後,添加的屬性名稱必須是約定的。否則會報錯 AttributeError
class Test:
testparam = 0
__slots__ = ("name","age","__one")
def __init__(self):
self.__one = 10
def __get_1(self):
print(self.one)
def get_1(self):
print(self.__one)
類中,方法的第一個參數總是接收方法調用的隱性主題,也就是實例對象。self.
運算符重載:
__repr__, __str__ 打印,轉換,當類需要進行print 打印類本身時,可以重載此函數。
Python中的重載運算符都是類似於此。常見的運算符重載方法可以搜索獲得。
class Readimg:
def __init__(self,filePath):
self.filePath = filePath
with open(filePath,'rb') as file:
bitdata = file.read(4*4)
data = struct.unpack(">4i",bitdata)
self.magic_num,self.num_images,self.row,self.columns=data
def saveimg(self,imgbuf,imgname,row = 28,columns = 28):
print("Enter saveimg ",type(imgname))
print("type imgbuf ",type(imgbuf))
#img = np.array(list(imgbuf)).reshape(row,columns)
#cv.imwrite("%s.png"%imgname,img)
def readimg(self):
with open(self.filePath,'rb') as file:
file.seek(4*4)
#i = 1
print("row = %d, columns = %d"%(self.row,self.columns))
imgbuf = file.read(self.row * self.columns)
img = struct.unpack('>784B',imgbuf)
Readimg.saveimg(self,list(img),"img0")
輸出:
row = 28, columns = 28
Enter saveimg <class 'str'>
type imgbuf <class 'list'>
當類中定義的函數中,第一個參數是比較特殊的,它總是接受將方法調用視爲隱含主體的實例對象,按慣例定義爲self。寫成其他名字時,也會默認爲實例對象。 內部調用時有兩種方法:1、 直接使用self. 調用。 self.saveimg(list(img),”img0”)
2、 使用類名調用, 函數參數中加入 self 參數。 Readimg.saveimg(self,list(img),"img0")
技巧:
使用timeit 統計函數執行時間。
通常在一段程序的前後都用上time.time(),然後進行相減就可以得到一段程序的運行時間,不過python提供了更強大的計時庫:timeit
timeit
通常在一段程序的前後都用上time.time(),然後進行相減就可以得到一段程序的運行時間,不過python提供了更強大的計時庫:timeit
#導入timeit.timeit
from timeit import timeit
#看執行1000000次x=1的時間:
timeit('x=1')
#看x=1的執行時間,執行1次(number可以省略,默認值爲1000000):
timeit('x=1', number=1)
#看一個列表生成器的執行時間,執行1次:
timeit('[i for i in range(10000)]', number=1)
#看一個列表生成器的執行時間,執行10000次:
timeit('[i for i in range(100) if i%2==0]', number=10000)
測試一個函數的執行時間:
from timeit import timeit
def func():
s = 0
for i in range(1000):
s += i
print(s)
# timeit(函數名_字符串,運行環境_字符串,number=運行次數)
t = timeit('func()', 'from __main__ import func', number=1000)
print(t)
此程序測試函數運行1000次的執行時間