菜鳥學習python程式設計--雜記 (不定期更新)
目錄
1.bool型別的形參+return 的合理使用
bool型的形參,代表的是一種情況,搭配return使用,一旦執行,return後面的語句不再執行。
比如下面代表的是隻去除左邊的空白。
2.總是習慣於for i in range這種,
其實當i有明確含義時,如下for col in xrange(w)
3.for與np的聯合使用,
這樣就不用兩個for巢狀使用
例子:
如下:for col in xrange(w):
if(im[:,col,:]
備註:這裡的all是np當中的,(im[:,col,:]>240)返回一個bool型別的ndarray,也可以all(im[:,col,:]>240)
當你腦海中想到每一個,的時候,可以考慮any all。如:一列當中每一行的元素都要小於240,表明這一列是空白的。
#############多的地方代表要學習的地方 def remove_zero_padding(image, only_left=False):. '''OCR分割出性別後去除兩邊空白的區域''' h, w = image.shape[:2] index_left = 0 index_right = w - 1 for col in range(w): if (image[:, col] >= 240).all(): index_left = col + 1 else: break if only_left:############# return image[:, index_left:]############# for col in range(w):########## if (image[:, w - col - 1] >= 240).all():############# index_right = w - col - 1 else: break return image[:, index_left:index_right]
4. import copy
out = copy.deepcopy(im) 重新重建一個np,和原先的沒關係
out = im.copy() 也可以,操作的時候如下
e.g. im = remove_zero_padding(im.copy()[:, 5:-5])
5. np.clip(data,min,max),
小於min的都為min,大於max都變為max
x=np.array([1,2,3,5,6,7,8,9])
np.clip(x,3,8)
array([3, 3, 3, 5, 6, 7, 8, 8])
6. np.where 兩種用法
- np.where(condition, x, y)
滿足條件(condition),輸出x,不滿足輸出y。image = np.where(image >= 240, 255,image)
-
np.where(condition)
a = np.array([2,4,6,8,10])
a[np.where(a > 5)] # 等價於 a[a>5] array([ 6, 8, 10])
7. np.oneslike(x)
返回一個用1填充的跟x 形狀和型別 一致的陣列。
8. s_list = np.random.choice(self.schools_majors, batch_size)
#隨機選取多少個學校或專業
9. np.expand_dims(im, axis=0) n h w c
10. .format
索引: python3中 print("{0}/{1}".format(i,100000),end="\r"),{0}表示第0個,{1}表第一個。
for i in range(100000):
print("{0}/{1}".format(i,100000),end="\r")
精度:print('{:.3f}'.format(123.45678)) 四捨五入
#類似字典
line = "{pic_id},{sex},{nation},{weight} kg,{blood_type},{native_place}".format(pic_id=pic_id,
sex=sex,
nation=nation,
weight=weight,
blood_type=blood_type,
native_place=native_place) + \
"," + ",".join([school['gaozhong'], major['gaozhong'], xuewei['gaozhong'], time['gaozhong'], graduate['gaozhong']]) + \
"," + ",".join([school['dazhuan'], major['dazhuan'], xuewei['dazhuan'], time['dazhuan'], graduate['dazhuan']]) + \
"," + ",".join([school['benke'], major['benke'], xuewei['benke'], time['benke'], graduate['benke']]) + \
"," + ",".join([school['yanjiusheng'], major['yanjiusheng'], xuewei['yanjiusheng'], time['yanjiusheng'], graduate['yanjiusheng']]) + \
",無" * 5 # 高中、專科、本科、研究生、其它(全是無)
11. z.reshape(-1) 變成一行 z.reshape(-1,1)變成一列
原始碼:x_image = tf.reshape(x, [-1, 1,28, 28])
這裡是將一組影象矩陣x重建為新的矩陣,該新矩陣的維數為(a,1,28,28),其中-1表示a由實際情況來定。例如,x是一組影象的矩陣(假設是50張,大小為56×56),則執行
x_image = tf.reshape(x, [-1, 1,28, 28]) nchw
可以計算a=50×56×56/28/28/1=200。即x_image的維數為(200,1,28,28)。
12. continue遇到一種情形先跳過,這次迴圈
跳過太白的圖片
if origin_im.mean() > 250:
continue
13.map 對映 map(表示式, 列表等) 不用for迴圈
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函式
[1, 4, 9, 16, 25]
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]