【機器學習】Python 快速入門筆記
Xu An 2018-3-7
1、Python print
#在Python3.X中使用print()進行輸出,而2.x中使用()會報錯 print("hello world") print('I\'m apple') #如果全部使用單引號,則需要在前面加上轉義字符\+引號 print('apple'+'pear') print('apple'+str(4)) #將數字轉換為字符串並打印 print(int("1")+2)#將字符串轉換為整數類型
2、pyhton數值運算
print(2**2) #冪運算為** print(10%3) #取余數為% print(9//4) #取整數為//
3、自變量定義
a,b,c=1,2,3 #一次定義多個變量 print(a,b,c)
4、while循環
condition=1 while condition<10: print(condition) condition+=1
5、for循環(相當於叠代器)
x=1 y=2 z=3 if x<y<z: print("x is less than y")
6、if-else語句
if x<y: print("x<y") else: print("x>y")
7、if-elif-else
if x<y: print("x<y") elif x==y: print("") else: print("x>y")
8、函數定義
def add(a,b): #在python中定義函數需要使用def() c=a+b print("This is the result of the addtion:",c) add(1,3)
9、默認函數參數
def car(price,color='red',second_hand=True): #在函數參數後面加=“默認值”可以完成默認值的賦值 #bool類型中的參數需要大寫True、Flase #需要把默認參數放到變量的後面 print('price',price, 'color',color, 'second_hand',second_hand, ) car(1000)
10、變量類型
'''
(1)全局變量
在模塊內、所有函數外、class外的變量,可以被全局共享,也可以被外部文件共享
全局變量使用時,需要使用global顯式聲明
如果不將全局變量更新,一般不需要加global聲明
如果有重新賦值,又沒有在函數內部使用global聲明時,相當於在內部創建了一個同名的局部變量
同名局部變量優先級高於未顯式聲明的全局變量
'''
APPLE=10 #全局變量需要在函數外部定義 def test10_01(): global APPLE #在函數內部定義全局變量 APPLE=20 #在函數內聲明的局部變量的優先級高於全局變量 print(APPLE) test10_01()
'''
(2)局部變量
在函數內、class方法內(未加self修飾)
生命周期在函數執行時,當函數執行完畢後局部變量消亡
'''
def test10_02(): city='shijiazhuang' print(city)
'''
(3)靜態變量(類變量)
通過類名直接訪問,也可以通過實例名直接訪問,變量在類中、實例間全局共享
'''
# class foo: # all=0 # def add(self): # foo.q+=1 # ins_1=foo() #實例化對象1 # ins_2=foo() #實例化對象2 # print(ins_1.all) #0 # print(ins_2.all) #0 # print(foo.all) #0 # ins_1.add() #靜態全局變量加1
'''
(4)實例變量
對於模塊來說,擁有自己的全局變量,可以供自己內部的類,函數使用
對於類或者方法來說,有自己的局部變量,供自己內部使用
對於類,有了靜態變量,可以供內部和有繼承關系的父子使用
實例間各自的局部變量需要靠動態綁定多態實現
'''
class foo_1: all=0 def __init__(self,name): self.name=name def add(self): foo.q+=1
'''
(5)總結
私有變量:自己獨享的變量,如函數和方法的局部變量,實例變量
公有變量:需要在一定範圍內共享,達到同步的目的,如模塊內的代碼共享的全局變量,類與子類之間共享的靜態變量
'''
11、文件寫入
text="This is my first text.\nThis is next line\n" #使用\n表示換行,主要換行指令與C++一致 print(text) my_file=open('1.txt','w') #open可以打開一個文件,open(‘文件路徑’,‘形式’),形式w為可寫形式,r為只讀形式 my_file.write(text) #在文件中寫入相應的語句 my_file.close() #切記在文件寫入後要使用close方法關閉文件 print('Flie writing completed.')
12、文字內容追加
my_file=open('1.txt','a') #方式a是append的縮寫,表示文件的追加模式 append_text="this is appened text" my_file.write(append_text) my_file.close()
# 13、讀文件
my_file=open('1.txt','r') #r為讀模式 content=my_file.read() #讀取文件內容需要使用read()方法 second_read=my_file.readline() third_read=my_file.readline() #readline為逐行輸出文字 all_read=my_file.readlines() #逐行讀取後會將讀取的元素按行放置在一個列表中 print(content,'second_read',second_read,'third_read',third_read,'all_read',all_read)
14、類(class)
class Calculator: #類一般為大寫 def __init__(self,name,price): #構造函數,在進行對象實例化時必須賦值,前面需要加上self self.name=name self.price=price name="Calculator" price=10 def add(self,x,y): print(self.name) #如果要在類內調用本身的方法,需要加上self.屬性名或self.方法名 result=x+y print(result) def minus(self,x,y): result=x-y print(result) def times(self,x,y): result=x*y print(result) def devide(self,x,y): result=x/y print(result) newcalulator=Calculator('name',10) print(newcalulator.name)
15、input
a_input=input('Please give me a number:') #input的功能為輸入,其後面的括號為提示信息,input的返回值為輸入的內容(是str類型),並賦值給對應的參數 int_input=int(a_input) #對字符串需要轉換為int類型後進行判斷 if int_input==1: print('your input is 1') elif int_input==2: print('your input is 2') else: print('your input number is other')
16、元組 使用小括號或者不使用括號
a_tuple=(1,2,3,43) #元組可以用小括號的形式,也可以不加小括號 another_tuple=1,12,43,23 for x in a_tuple: print(x)
17、列表 使用中括號
a_list=[12,34,23,43] for x in a_list: #將list的值使用for循環放到x中,之後打印出來 print(x) for index in range(len(a_list)): #range()會生成一個叠代器,index為索引 print("index=",index,'number in list=',a_list[index]) a=[1,2,3,4,5] a.append(0) #在列表後面追加一個元素 print(a) a.insert(1,0) #insert(添加位置,數值) a.remove(2) #remove(第一次出現的數值) print(a[3:5]) a.index(1)#列表中第一次出現該數值的索引 a.sort(reverse=True) #默認為從小到大進行排序,加入reverse則進行從大到小進行排序 print(a)
18、多維列表
a=[1,2,3,4,5] multi_dim_a=[[1,2,3],[123,312,4],[12,43,1]] print(multi_dim_a[1][1]) #使用[][]進行索引
19、字典 使用大括號
d={'apple':1,'pear':2,'orange':3} #冒號前面的為key,後面的為內容,字典的key唯一,如果不唯一則記住後面的元素,其不能是列表,以保證其唯一性要求 print(d['apple']) #打印字典的值 del d['pear'] #從字典中刪除元素 d['b']=20 #加入元素到字典 print(d) #因為字典采用hash存儲,所以字典是一個無序的容器
20、import模塊
#方法一: # import time #直接使用模塊名進行後續操作 # print(time.localtime()) # 方法二: # import time as t #如果模塊名太長可以使用簡稱 #方法三: # from time import localtime 只引入模塊的某個功能 # print(localtime()) #如果使用本方法,可以不用寫time.localtime,而直接寫localtime() #方法四: from time import * #加*可以結束 print(localtime())
21、引入自己的模塊
# 確保自己的模塊(同為.py文件)和本文件在同一個目錄下, # import m1 #自己的模塊名,其中定義了函數 # m1.function() 直接調用其函數即可,在macox中,其包目錄在site-package中,如果將自建模塊放入其中,則可以直接調用
22、break&continue
a=True while a: b=input('Please enter something:') if b!='': print('enter is not blank') break
23、錯誤處理
try: File=open('12','r') except Exception as e: print('there is no file named 12') response=input('do you want to creat a new file?(Y/N)') if response =='y'or'Y': #邏輯運算符 或or 且and 非not print('the file is created') else: pass #跳過
24、zip(將兩個列表合並為一個列表項) lambda map
a=[1,2,3] b=[4,5,6] list(zip(a,b)) #zip返回為一個對象,如果想將其可視化,需要將其轉化為list進行合並 for i,j in zip(a,b): print(i/2,j/2) #生成一個叠代器進行輸出 fun1=lambda x,y:print(x+y) fun1(2,3) def fun1(x,y): return(x+y) #實現參數綁定 print(fun1,[1,3],[2,8])
25、shallow copy &deep copy
import copy a=[1,2,3] b=a print(id(a)) #輸出變量的唯一id,是賦值,b只是將a的地址進行了復制,而沒有進行實際的變量值的拷貝 print(id(b)) c=copy.copy(a) print('id of a:',id(a)) print('id of c:',id(c)) #淺拷貝,id不同,第一層空間地址不同,但是第二層空間(數組第二圍)開始地址相同 d=copy.deepcopy(a) print('id of a:',id(a)) print('id of c:',id(d)) #深拷貝,id不同,從第一層空間開始地址已經完全不同
# 26、threading 線程
# 27、multiprocessing 多核心
# 28、tkinter GUI界面
29、pickle 保存代碼
import pickle # a_dic={'fruit':['apple','pear'],'vegetable':['tomato','cumcuber']} # file =open('pickle_exm.pickle','wb') # pickle.dump(a_dic,file) # file.close() # file=open('pickle_exm.pickle','rb') # a_dic=pickle.load(file) #將之前保存的代碼打開 # file.close()
#或者自動關閉方案
with open('pickle_exm.pickle','rb') as file: a_dic=pickle.load(file)
30、使用set尋找不同
char_list=['a','b','c','c'] print(set(char_list)) #使用set進行不同查找,輸出結果為非重復序列,按hash排序 sentence='welcome to shijiazhuang' print(set(sentence)) #可以分辨句子中的不同字母,並以單個的形式呈現
# 31、正則表達式(待補充)
import re #引入正則表達式 pattern1="cat" pattern2='dog' string="dog runs to cat" print(pattern1 in string) #使用in來判斷單詞是否在目標語句中 #查找 print(re.search(pattern1,string))#使用正則表達式進行查找,查找到的內容會被以對象的形式返回 #匹配多種可能——使用[] print(re.search(r"r[A-Z0-9]n",'dog runs to the cat'))
【機器學習】Python 快速入門筆記