大體上把Python中的資料類型分為如下幾類:
Number(數字) 包括int,long,float,complex String(字串) 例如:hello,"hello",hello List(列表) 例如:[1,2,3],[1,2,3,[1,2,3],4] Dictionary(字典) 例如:{1:"nihao",2:"hello"} Tuple(元組) 例如:(1,2,3,abc) Bool(布爾) 包括True、False
由於Python中認為所有的東西都是對象,所以Python不用像其它一些進階語言那樣主動聲明一個變數的類型。
例如我要給一個變數i賦值100,python的實現 :
i=100
C#的實現:
int i = 100;
下面一一簡單介紹這幾種資料類型
數字類型
int和long
之所以要把int和long放在一起的原因是python3.x之後已經不區分int和long,統一用int。python2.x還是區分的。下面我以Python2.7為例:
>>> i = 10 >>> type(i) >>> i=10000000000 >>> type(i)
那麼為什麼10就是int,10000000000就是long呢,當然這就和int的最大值有關了,int類型的最大值為231-1,即2147483647,也可以用sys.maxint。
>>> 2**31-1 2147483647L >>> sys.maxint 2147483647
為什麼用上面的方法求的值就是long型的呢(數字後面加‘L'表示是long型),因為2**31的值為2147483648,這個值是一個long型,用一個long型減去1,結果還是一個long,但實際上int型的最大值就是2147483647
>>> type(2147483647) >>> type(2147483648)
float類型
float類型和其它語言的float基本一致,浮點數,說白了,就是帶小數點的數,精度與機器相關。例如:
>>> i = 10000.1212 >>> type(i)
complex:複數類型,具體含義及用法可自行查看相關文檔。
字串類型
字串的聲明有三種方式:單引號、雙引號和三引號(包括三個單引號或三個雙引號)。例如:
>>> str1 = 'hello world' >>> str2 = "hello world" >>> str3 = '''hello world''' >>> str4 = """hello world""" >>> print str1 hello world >>> print str2 hello world >>> print str3 hello world >>> print str4 hello world
Python中的字串有兩種資料類型:str類型和unicode類型。str類型採用的ASCII編碼,也就是說它無法表示中文。unicode類型採用unicode編碼,能夠表示任一字元,包括中文及其它語言。並且python中不存在像c語言中的char類型,就算是單個字元也是字串類型。字串預設採用的ASCII編碼,如果要顯示聲明為unicode類型的話,需要在字串前面加上'u'或者'U'。例如:
>>> str1 = "hello" >>> print str1 hello >>> str2 = u"中國" >>> print str2 中國
由於項目中經常出現對字串的操作,而且由於字串編碼問題出現的問題很多,下面,來說一下關於字串的編碼問題。在與python打交道的過程中經常會碰到ASCII、Unicode和UTF-8三種編碼。具體的介紹請參見這篇文章。我簡單的理解就是,ASCII編碼適用英文字元,Unicode適用於非英文字元(例如中文、韓文等),而utf-8則是一種儲存和傳送的格式,是對Uncode字元的再編碼(以8位為單位編碼)。例如:
u = u'漢' print repr(u) # u'\u6c49' s = u.encode('UTF-8') print repr(s) # '\xe6\xb1\x89' u2 = s.decode('UTF-8') print repr(u2) # u'\u6c49'
解釋:聲明unicode字串”漢“,它的unicode編碼為”\u6c49“,經過utf-8編碼轉換後,它的編碼變成”\xe6\xb1\x89“。
對於編碼的經驗總結:
1.在python檔案頭聲明編碼格式 ;
#-*- coding: utf-8 -*-
2.將字串統一聲明為unicode類型,即在字串前加u或者U;
3.對於檔案讀寫的操作,建議適用codecs.open()代替內建的open(),遵循一個原則,用哪種格式寫,就用哪種格式讀;
假設在一個以ANSI格式儲存的文字檔中有“中國漢字”幾個字,如果直接用以下代碼,並且要在GUI上或者在一個IDE中列印出來(例如在sublime text中,或者在pydev中列印),就會出現亂碼或者異常,因為codecs會依據文本本身的編碼格式讀取內容:
f = codecs.open("d:/test.txt") content = f.read() f.close() print content
改用如下方法即可(只對中文起作用):
# -*- coding: utf-8 -*- import codecs f = codecs.open("d:/test.txt") content = f.read() f.close() if isinstance(content,unicode): print content.encode('utf-8') print "utf-8" else: print content.decode('gbk').encode('utf-8')
清單類型
列表是一種可修改的集合類型,其元素可以是數字、string等基本類型,也可以是列表、元組、字典等集合對象,甚至可以是自訂的類型。其定義方式如下:
>>> nums = [1,2,3,4] >>> type(nums) >>> print nums [1, 2, 3, 4] >>> strs = ["hello","world"] >>> print strs ['hello', 'world'] >>> lst = [1,"hello",False,nums,strs] >>> type(lst) >>> print lst [1, 'hello', False, [1, 2, 3, 4], ['hello', 'world']]
用索引的方式訪問列表元素,索引從0開始,支援負數索引,-1為最後一個.
>>> lst = [1,2,3,4,5] >>> print lst[0] 1 >>> print lst[-1] 5 >>> print lst[-2] 4
支援分區操作,可訪問一個區間內的元素,支援不同的步長,可利用分區進行資料插入與複製操作
nums = [1,2,3,4,5] print nums[0:3] #[1, 2, 3] #前三個元素 print nums[3:] #[4, 5] #後兩個元素 print nums[-3:] #[3, 4, 5] #後三個元素 不支援nums[-3:0] numsclone = nums[:] print numsclone #[1, 2, 3, 4, 5] 複製操作 print nums[0:4:2] #[1, 3] 步長為2 nums[3:3] = ["three","four"] #[1, 2, 3, 'three', 'four', 4, 5] 在3和4之間插入 nums[3:5] = [] #[1, 2, 3, 4, 5] 將第4和第5個元素替換為[] 即刪除["three","four"]
支援加法和乘法操作
lst1 = ["hello","world"] lst2 = ['good','time'] print lst1+lst2 #['hello', 'world', 'good', 'time'] print lst1*5 #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world']
列表所支援的方法,可以用如下方式查看列表支援的公用方法:
>>> [x for x in dir([]) if not x.startswith("__")] ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] def compare(x,y): return 1 if x>y else -1 #【append】 在列表末尾插入元素 lst = [1,2,3,4,5] lst.append(6) print lst #[1, 2, 3, 4, 5, 6] lst.append("hello") print lst #[1, 2, 3, 4, 5, 6] #【pop】 刪除一個元素,並返回此元素的值 支援索引 預設為最後一個 x = lst.pop() print x,lst #hello [1, 2, 3, 4, 5, 6] #預設刪除最後一個元素 x = lst.pop(0) print x,lst #1 [2, 3, 4, 5, 6] 刪除第一個元素 #【count】 返回一個元素出現的次數 print lst.count(2) #1 #【extend】 擴充列表 此方法與“+”操作的不同在於此方法改變原有列表,而“+”操作會產生一個新列表 lstextend = ["hello","world"] lst.extend(lstextend) print lst #[2, 3, 4, 5, 6, 'hello', 'world'] 在lst的基礎上擴充了lstextend進來 #【index】 返回某個值第一次出現的索引位置,如果未找到會拋出異常 print lst.index("hello") #5 #print lst.index("kitty") #ValueError: 'kitty' is not in list 出現異常 #【remove】 移除列表中的某個元素,如果待移除的項不存在,會拋出異常 無傳回值 lst.remove("hello") print lst #[2, 3, 4, 5, 6, 'world'] "hello" 被移除 #lst.remove("kitty") #ValueError: list.remove(x): x not in list #【reverse】 意為反轉 沒錯 就是將列表元素倒序排列,無傳回值 print lst #[2, 3, 4, 5, 6, 'world'] lst.reverse() print lst #[2, 3, 4, 5, 6, 'world'] #【sort】 排序 print lst #由於上面的反轉 目前排序為 ['world', 6, 5, 4, 3, 2] lst.sort() print lst #排序後 [2, 3, 4, 5, 6, 'world'] nums = [10,5,4,2,3] print nums #[10,5,4,2,3] nums.sort(compare) print nums #[2, 3, 4, 5, 10]
列錶轉換為迭代器。
所謂的迭代器就是具有next方法(這個方法在調用時不需要任何參數)的對象。在調用next方法時,迭代器會返回它的下一個值。如果next方法被調用,但迭代器沒有值可以返回,就會引發一個StopIteration異常。迭代器相對於列表的優勢在於,使用迭代器不必一次性將列表加入記憶體,而可以依次訪問列表的資料。
依然用上面的方法查看迭代器的公用方法:
lst = [1,2,3,4,5] lstiter = iter(lst) print [x for x in dir(numiter) if not x.startswith("__")] >>>['next']
沒錯,只有next一個方法,對於一個迭代器,可以這樣操作:
lst = [1,2,3,4,5] lstiter = iter(lst) for i in range(len(lst)): print lstiter.next() #依次列印 1 2 3 4 5
元群組類型
元群組類型和列表一樣,也是一種序列,與列表不同的是,元組是不可修改的。元組的聲明如下:
lst = (0,1,2,2,2) lst1=("hello",) lst2 = ("hello") print type(lst1) # 只有一個元素的情況下後面要加逗號 否則就是str類型 print type(lst2) #
字典類型
字典類型是一種索引值對的集合,類似於C#中的Dictionary或js中的json對象。其初始化方法如下:
dict1 = {} print type(dict1) # 聲明一個空字典 dict2 = {"name":"kitty","age":18} #直接聲明字典類型 dict3 = dict([("name","kitty"),("age",18)]) #利用dict函數將列錶轉換成字典 dict4 = dict(name='kitty',age=18) #利用dict函數通過關鍵字參數轉換為字典 dict5 = {}.fromkeys(["name","age"]) #利用fromkeys函數將key值列表產生字典,對應的值為None {'age': None, 'name': None}
字典基本的操作方法:
#【添加元素】 dict1 = {} dict1["mykey"] = "hello world" #直接給一個不存在的索引值對賦值 即時添加新元素 dict1[('my','key')] = "this key is a tuple" #字典的鍵可以是任何一中不可變類型,例如數字、字串、元組等 #【索引值對個數】 print len(dict1) #【檢查是否含有鍵】 print "mykey" in dict1 #True 檢查是否含有鍵為mykey的索引值對 print "hello" in dict1 #False #【刪除】 del dict1["mykey"] #刪除鍵為mykey的索引值對
繼續利用上面的方法查看字典的所有公用方法:
>>> [x for x in dir({}) if not x.startswith("__")] ['clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
dict.clear() 刪除字典中所有元素
dict.copy() 返回字典(淺複製)的一個副本
dict.get(key,default=None) 對字典dict 中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default 的值(注意,參數default 的預設值為None)
dict.has_key(key) 如果鍵(key)在字典中存在,返回True,否則返回False. 在Python2.2版本引入in 和not in 後,此方法幾乎已廢棄不用了,但仍提供一個 可工作的介面。
dict.items() 返回一個包含字典中(鍵, 值)對元組的列表
dict.keys() 返回一個包含字典中鍵的列表
dict.values() 返回一個包含字典中所有值的列表
dict.iter() 方法iteritems(), iterkeys(), itervalues()與它們對應的非迭代方法一樣,不同的是它們返回一個迭代器,而不是一個列表。
dict.pop(key[, default]) 和方法get()相似,如果字典中key 鍵存在,刪除並返回dict[key],如果key 鍵不存在,且沒有給出default 的值,引發KeyError 異常。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。
dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。
布爾類型
布爾類型即True和False,和其它語言中的布爾類型基本一致。下面列出典型的布爾值
print bool(0) #False print bool(1) #True print bool(-1) #True print bool([]) #False print bool(()) #False print bool({}) #False print bool('') #False print bool(None) #False