六、數據結構
python有三種內建的數據結構:列表、元組和字典。
1. 列表
list是處理一組有序項目的數據結構,列表是可變的數據結構。列表的項目包含在方括號[]中,eg: [1, 2, 3], 空列表[]。判斷列表中是否包含某項可以使用in, 比如 l = [1, 2, 3]; print 1 in l; #True;支持索引和切片操作;索引時若超出范圍,則IndexError;使用函數len()查看長度;使用del可以刪除列表中的項,eg: del l[0] # 如果超出范圍,則IndexError
list函數如下:
append(value) ---向列表尾添加項value
l = [1, 2, 2] l.append(3) #[1, 2, 2, 3]
count(value) ---返回列表中值為value的項的個數,溢出返回0
l = [1, 2, 2] print l.count(2) # 2
extend(list2) ---向列表尾添加列表list2
l = [1, 2, 2] x = [10, 20] l.extend(x) print l #[1, 2, 2, 10, 20]
index(value, [start, [stop]]) ---返回列表中第一個出現的值為value的索引,如果沒有,則異常 ValueError
l = [1, 2, 2]
a = 4
try:
print l.index(a)
except ValueError, ve:
print "there is no %d in list" % a
insert(i, value) ---向列表i位置插入項vlaue,如果沒有i,則添加到列表尾部
l = [1, 2, 2] l.insert(1, 100) print l #[1, 100, 2, 2] l.insert(100, 1000) print l #[1, 100, 2, 2, 1000]
pop([i]) ---返回i位置項,並從列表中刪除;如果不提供參數,則刪除最后一個項;如果提供,但是i超出索引范圍,則異常IndexError
l = [0, 1, 2, 3, 4, 5] print l.pop() # 5 print l #[0, 1, 2, 3, 4] print l.pop(1) #1 print l #[0, 2, 3, 4] try: l.pop(100) except IndexError, ie: print "index out of range"
remove(value) ---刪除列表中第一次出現的value,如果列表中沒有vlaue,則異常ValueError
l = [1, 2, 3, 1, 2, 3] l.remove(2) print l #[1, 3, 1, 2, 3] try: l.remove(10) except ValueError, ve: print "there is no 10 in list"
reverse() ---列表反轉
l = [1, 2, 3] l.reverse() print l #[3, 2, 1]
sort(cmp=None, key=None, reverse=False) ---列表排序
l5 = [10, 5, 20, 1, 30] l5.sort() print l5 #[1, 5, 10, 20, 30] l6 = ["bcd", "abc", "cde", "bbb"] l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1])) print l6 #['abc', 'bbb', 'bcd', 'cde'] l7 = ["bcd", "abc", "cde", "bbb", "faf"] l7.sort(key = lambda s: s[1]) print l7 #['faf', 'abc', 'bbb', 'bcd', 'cde'] #cmp(x,y) 比較2個對象,前者小於后者返回-1,相等則返回0,大於后者返回1. #lambda Python的匿名函數
2. 元組
tuple和list十分相似,但是tuple是不可變的,元組通過圓括號中用逗號分割的項定義;支持索引和切片操作;可以使用 in 查看一個元素是否在tuple中。空元組();只含有一個元素的元組("a",) #需要加個逗號
優點:tuple比list速度快;對不需要修改的數據進行'寫保護',可以是代碼更安全
tuple與list可以相互轉換,使用內置的函數list()和tuple()。
l = [1, 2, 3] print l # [1, 2, 3] t = tuple(l) print t # (1, 2, 3) l1 = list(t) print l1 #[1, 2, 3]
元組最通常的用法是用在打印語句,如下例:
name = "LinZhenjie" age = 23 print "Name: %s; Age: %d" % (name, age) # Name: LinZhenjie; Age: 23
tuple 函數如下:
count(value) ---返回元組中值為value的元素的個數
t = (1, 2, 3, 1, 2, 3) print t.count(2) # 2
index(value, [start, [stop]]) ---返回列表中第一個出現的值為value的索引,如果沒有,則異常 ValueError
t = (1, 2, 3, 1, 2, 3) print t.index(3) # 2 try: print t.index(4) except ValueError, ve: print "there is no 4 in tuple" # there is no 4 in tuple
3. 字典
字典由鍵值對組成,鍵必須是唯一的;eg: d = {key1:value1, key2:value2};空字典用{}表示;字典中的鍵值對是沒有順序的,如果想要
一個特定的順序,那么使用前需要對它們排序;d[key] = value,如果字典中已有key,則為其賦值為value,否則添加新的鍵值對key/value;使
用del d[key] 可以刪除鍵值對;判斷字典中是否有某鍵,可以使用in 或 not in;
d = {} d["1"] = "one" d["2"] = "two" d["3"] = "three" del d["3"] for key, value in d.items(): print "%s --> %s" % (key, value) #1 --> one #2 --> two
dict 函數如下:
clear() ---刪除字典中所有元素
d1 = {"1":"one", "2":"two"} d1.clear() print d1 # {}
copy() ---返回字典的一個副本(淺復制)
d1 = {"1":"one", "2":"two"} d2 = d1.copy() print d2 #{'1': 'one', '2': 'two'}
dict.fromkeys(seq,val=None) ---創建並返回一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值(默認為None)
l = [1, 2, 3] t = (1, 2, 3) d3 = {}.fromkeys(l) print d3 #{1: None, 2: None, 3: None} d4 = {}.fromkeys(t, "default") print d4 #{1: 'default', 2: 'default', 3: 'default'}
get(key,[default]) ---返回字典dict中鍵key對應值,如果字典中不存在此鍵,則返回default 的值(default默認值為None)
d5 = {1:"one", 2:"two", 3:"three"} print d5.get(1) #one print d5.get(5) #None print d5.get(5, "test") #test
has_key(key) ---判斷字典中是否有鍵key
d6 = {1:"one", 2:"two", 3:"three"} print d6.has_key(1) #True print d6.has_key(5) #False
items() ---返回一個包含字典中(鍵, 值)對元組的列表
d7 = {1:"one", 2:"two", 3:"three"} for item in d7.items(): print item #(1, 'one') #(2, 'two') #(3, 'three') for key, value in d7.items(): print "%s -- %s" % (key, value) #1 -- one #2 -- two #3 -- three
keys() ---返回一個包含字典中所有鍵的列表
d8 = {1:"one", 2:"two", 3:"three"} for key in d8.keys(): print key #1 #2 #3
values() ---返回一個包含字典中所有值的列表
d8 = {1:"one", 2:"two", 3:"three"} for value in d8.values(): print value #one #two #three
pop(key, [default]) ---若字典中key鍵存在,刪除並返回dict[key],若不存在,且未給出default值,引發KeyError異常
d9 = {1:"one", 2:"two", 3:"three"} print d9.pop(1) #one print d9 #{2: 'two', 3: 'three'} print d9.pop(5, None) #None try: d9.pop(5) # raise KeyError except KeyError, ke: print "KeyError:", ke #KeyError:5
popitem() ---刪除任意鍵值對,並返回該鍵值對,如果字典為空,則產生異常KeyError
d10 = {1:"one", 2:"two", 3:"three"} print d10.popitem() #(1, 'one') print d10 #{2: 'two', 3: 'three'}
setdefault(key,[default]) ---若字典中有key,則返回vlaue值,若沒有key,則加上該key,值為default,默認None
d = {1:"one", 2:"two", 3:"three"} print d.setdefault(1) #one print d.setdefault(5) #None print d #{1: 'one', 2: 'two', 3: 'three', 5: None} print d.setdefault(6, "six") #six print d #{1: 'one', 2: 'two', 3: 'three', 5: None, 6: 'six'}
update(dict2) ---把dict2的元素加入到dict中去,鍵字重復時會覆蓋dict中的鍵值
d = {1:"one", 2:"two", 3:"three"} d2 = {1:"first", 4:"forth"} d.update(d2) print d #{1: 'first', 2: 'two', 3: 'three', 4: 'forth'}
viewitems() ---返回一個view對象,(key, value)pair的列表,類似於視圖。優點是,如果字典發生變化,view會同步發生變化。在
迭代過程中,字典不允許改變,否則會報異常
d = {1:"one", 2:"two", 3:"three"} for key, value in d.viewitems(): print "%s - %s" % (key, value) #1 - one #2 - two #3 - three
viewkeys() ---返回一個view對象,key的列表
d = {1:"one", 2:"two", 3:"three"} for key in d.viewkeys(): print key #1 #2 #3
viewvalues() ---返回一個view對象,value的列表
d = {1:"one", 2:"two", 3:"three"} for value in d.viewvalues(): print value #one #two #three
4. 序列
序列類型是指容器內的元素從0開始的索引順序訪問,一次可以訪問一個或者多個元素;列表、元組和字符串都是序列;序列的兩個主要特點是
索引操作符和切片操作符;索引可以得到特定元素;切片可以得到部分序列;
numbers = ["zero", "one", "two", "three", "four"] print numbers[1] # one print numbers[-1] # four #print numbers[5] # raise IndexError print numbers[:] # ['zero', 'one', 'two', 'three', 'four'] print numbers[3:] # ['three', 'four'] print numbers[:2] # ['zero', 'one'] print numbers[2:4] # ['two', 'three'] print numbers[1:-1] # ['one', 'two', 'three']
切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之后)表示切片到哪里結束。 如果不指定第一個數,Python就從
序列首開始。如果沒有指定第二個數,則Python會停止在序列尾。 注意,返回的序列從開始位置 開始 ,剛好在結束位置之前 結束。即開始位置是
包含在序列切片中的,而結束位置被排斥在切片外。 可以用負數做切片。負數用在從序列尾開始計算的位置。
5. 綁定
當創建一個對象並給它賦一個變量的時候,這個變量僅僅“指向”那個對象,而不是表示這個對象本身! 也就是說,變量名指向計算機中存儲那個
對象的內存,這被稱作名稱到對象的綁定。
如果要復制一個列表或者類似的序列或者其他復雜的對象(不是如整數那樣的簡單對象),那么必須使用切片操作符來取得拷貝。