最初是在coursera上看的Python講課,後來在看Stanford Fei-fei Li的卷積神經網絡時看到Python Numpy教程,覺得簡潔明瞭,就當筆記記錄下來了。本處主要介紹以下幾個方面:
- Python
1、基本數據類型
2、容器
3、基本語句
4、函數和類
Python
1、基本數據類型
python的基本數據類型包括:整型、浮點型、布爾值和字符串。這些數據類型的操作與大多數高級語言類似:
整型和浮點型:與一般高級語言類似。
x=3 # 無需定義數據類型
print type(x) # 輸出<type 'int'>
y=2.5
print type(y) # 輸出<type 'float'>
常見操作符:
操作符 | 結果 | 操作符 | 結果 | |
---|---|---|---|---|
x+y | 求和 | x-y | 求差 | |
x*y | 求積 | x/y | 求商 | |
x//y | 商的整數 | x%y | 求餘 | |
-x | 求反 | abs(x) | 絕對值 | |
pow(x,y) | x**y |
注:Python常見操作中沒有自加
布爾型:Python包含了布爾型數據的常見操作,但是操作一般用英語單詞表示,而不是常見的&&或||。
t = True
f = False
print type(t) # 輸出<type 'bool'>
print t and f # 邏輯“與”; 輸出"False"
print t or f # 邏輯“或”; 輸出"True"
print not t # 邏輯“非”; 輸出"False"
print t != f # 邏輯“異或”;輸出"True"
在這裏我們可以看到,其他語言中用的&&在Python中會報錯,不適用。
字符串:Python有強大的字符串處理功能,這裏簡單介紹該數據類型。
hello = 'hello' # 字符串可以使用單引號
world = "world" # 也可以使用雙引號,並不用事先規定變量的名字
print hello # 輸出"hello"
print len(hello) # 字符串長度; 輸出"5"
hw = hello + ' ' + world # 字符串拼接
print hw # 輸出 "hello world"
hw12 = '%s %s %d' % (hello, world, 12) #轉換爲字符串格式
print hw12 # 輸出 "hello world 12"
由圖可見,Python的字符串具有強大的內置函數,更方便自然語言處理。更多更有效的內置函數操作可以看這個文檔。
2、容器
Python包含有多個內置的容器:列表、詞典、集合和元組。
列表:Python中的列表是最具有靈活性的容器類型,定義與常見數組比較類似,[],不同之處是列表能夠包含多種不同的數據類別。
xs = [3, 1, 2] # 創建列表
print xs, xs[2] # 輸出 "[3, 1, 2] 2"
print xs[-1] # 負下標指示列表最後一個元素;輸出"2"
xs[2] = 'foo' # 列表能夠包含不同的數據類型
print xs # 輸出"[3, 1, 'foo']"
xs.append('bar') # 在列表後面增加新的數據
print xs # 輸出"[3, 1, 'foo','bar']"
x = xs.pop() # 移除列表中最後的元素
print x, xs # 輸出 "bar [3, 1, 'foo']"
關於列表的詳細內置函數可以參考之前的文檔。,其中最常見的比較容易混淆的內置函數是append(L)和extend(L)。前者是將L作爲整體加入到原列表中,而後者則是將L變量中的所有元素加入到原變量中,對比見下圖:
除了基本的訪問外,Python中的列表還提供了類似數組的訪問方式:
nums = range(5) # 隨機產生一個包含5個整數的列表
print nums # 輸出"[0, 1, 2, 3, 4]"
print nums[2:4] # 從2到4的索引(不包含4);輸出"[2, 3]"
print nums[2:] # 從2到最後的索引;輸出"[2, 3, 4]"
print nums[:2] # 從列表起始到2的索引(exclusive);輸出"[0, 1]"
print nums[:] #輸出["0, 1, 2, 3, 4]"
nums[2:4] = [8, 9] # 修改2-4(不包含4)的數據
print nums # 輸出"[0, 1, 8, 8, 4]"
字典:字典是一個存儲關係(關鍵字:值),類似於C++中的map關聯容器,定義的是鍵和值之間的一對一關係。
dict1 = {'name' : 'Lyndon', 'age' : 24, 'sex' : 'Male'} #創建字典
print type(dict1) #輸出"<type 'dict'>"
print dict1['name'] #輸出"lyndon"
dict1['Age']=24 #創建新的字典元素
print dict1['Age'] #輸出"24"
del dict1['Age'] #刪除元素
字典本身也帶有很多內置函數,具體可以查看文檔。
集合(set):Python中的集合與C++類似,是一個無序不重複的元素集合,也可以包含各種不同的數據類型,用{}定義。
animals = {'cat', 'dog'}
print 'cat' in animals # 檢查元素'cat'是否在集合中;輸出"True"
animals.add('fish') # 增加元素到集合
print len(animals) # 集合中元素的數目; 輸出"3"
animals.add('cat') # 已經存在的元素不會被添加
print len(animals) # 輸出"3"
animals.remove('cat') # 從集合中移除元素
print len(animals) # 輸出"2"
集合也包含一些簡單的內置操作函數,具體可以查看文檔。
元組(tuples):元組與list的功能比較像,但是是不可以改變的,不可以增加刪除元素,只能重新整體賦值。因此其相關內置函數比較少。
更多的資料參考文檔。
3、基本語句
Python中的順序結構、條件結構和循環結構與常見高級語言比較類似,還是比較容易理解。不過Python中一定要注意的就是整個結構的作用域是通過縮進實現的,所以在編寫Python條件、循環等程序時,一定要注意縮進。
條件結構:即程序滿足一定的結構時,程序後面的語句纔會執行。
基本表達:
if x>0:
print 'x is positive'
(本處用ipython notebook實現,方便函數和結構語句的查看)
常見的比較符:>(大於),>=(大於等於),<(小於),<=(小於等於),==(等於),!=(不等於),and(與),or(或),not(非)
組合結構:
x=3
y=4
if x==y:
print 'x and y are equal'
elif x>y:
print 'x is greater than y'
else:
print 'x is less than y'
輸出:
此外,再介紹一個比較好用的錯誤代碼處理結構Try/Except
hours = raw_input("Enter Hours:") #輸入工作時間
rate = raw_input("Enter Rate:") #輸入單位時間工資
try:
h = float(hours) #如果是數字轉換成浮點型數據
r = float(rate)
except:
print 'Error. Invalid entry.' #否則輸出錯誤
quit() #退出程序
print 'Pay:',h*r #如果都正確,輸出工資
循環結構:當條件滿足時,反覆執行循環語句中的語句。主要也是分爲while和for循環兩種。
while循環:注意縮進和終止條件。
n=5
while n>0:
print n #輸出數據
n = n-1 #條件減少
for 循環:for循環在Python中似乎更常用,可以和各種容器、數組等組合使用
nums = [5,4,3,2,1]
for i in range(len(nums)): # 類似於C語言中的循環,i從0到4
print nums[i] # 輸出列表中數
print 'done!'
for i in nums: #直接輸出列表
print i
squares = [i**2 for i in nums]
print squares
# 列表
animals =['cat','dog','monkey']
for animal in animals:
print animal
#字典
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d: #i是字典中的關鍵字
legs = d[animal]
print 'A %s has %d legs' % (animal, legs)
輸出:
此外循環中常見的兩個關鍵字break和continue在Python中也具有相同的功能。break直接跳出循環,而continue則是跳出本次循環,繼續循環的內容。我們可以將上面的關係融合成一個整體的小程序。
while True:
hours = raw_input("Enter Hours:") #輸入工作時間
rate = raw_input("Enter Rate:") #輸入單位時間工資
if hours =='done' or rate =='done':
print "The program is done!"
break #如果輸入“done”,表示程序結束,直接退出
else:
try:
h = float(hours) #如果是數字轉換成浮點型數據
r = float(rate)
except:
print 'Error. Invalid entry.Please enter a number.' #否則輸出錯誤
continue #退出本次循環,繼續輸入
print 'Pay:',h*r #如果都正確,輸出工資
輸入輸出:
當我們輸入的不是數字時,程序轉到except,輸出”Error. Invalid entry.Please enter a number.”然後轉到continue,跳出本次循環,繼續輸入。而當我們輸入’done‘時,程序滿足if語句的條件,先輸出“The program is done!”,然後執行break,直接跳出循環。另外,如果有兩個循環嵌套,而break在內層循環,則執行break時只能跳出內層循環。
4、函數和類
Python中函數的定義和使用與C++也比較像,要注意的基本也是縮進。下面來看一個簡單的函數的例子:
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print sign(x)
輸出:
先定義了函數sign(x),帶參數。def是函數定義關鍵字。需要判斷數字的正負時,直接調用該函數即可。在同一個文件中,函數可以直接在前面定義,然後在主函數中調用即可。但是,當調用別的文件中的函數時,不能直接調用,需要import,後面再介紹。
def Hello(): #子函數
str="Hello world"
print(str);
if __name__=="__main__": #主函數
print("main")
Hello() #調用
輸出:
這裏只是簡單介紹了Python中函數的結構,更詳細內容,參考官方文檔。
Python中類的定義很直接,相比於C++來說簡單了很多(其實用多了python,會感覺很多方面都很容易上手)。
class Greeter:
# 構造函數
def __init__(self, name):
self.name = name # 創建實例變量
# 函數實例
def greet(self, loud=False):
if loud:
print 'HELLO, %s!' % self.name.upper()
else:
print 'Hello, %s' % self.name
def Bye(self, loud=False):
if loud:
print 'GOOD BYE, %s!' % self.name.upper()
else:
print 'Good bye, %s' % self.name
g = Greeter('Fred') # 構建類的實例
g.greet() # 調用函數
g.greet(loud=True) # 調用函數
g.Bye()
g.Bye(loud=True)
輸出:
關於類更詳細的介紹,可以參考文檔。