5 Python常用資料結構
Table of Contents 1 List 1.1 List 的使用 1.2 將List當作棧(Stack) 1.3 將List當作隊列 1.4 函數式程式設計工具 1.5 List Comprehensions 2 del 語句 3 Tuples 和 序列 4 Sets 5 Dictionaries 6 迴圈技術 7 更多的條件操作 8 比較序列操作
1 List
1.1 List 的使用 List 相關函數:append,extend,insert,remove,pop,index,count,sort,reverse
>>> a[3, 1, 2]>>> b[4, 7, 6, 10]>>> a.append(5)>>> a[3, 1, 2, 5]>>> a.extend(b)>>> a[3, 1, 2, 5, 4, 7, 6, 10]>>> a.insert(0,9)>>> a[9, 3, 1, 2, 5, 4, 7, 6, 10]>>> a.insert(1,8)>>> a[9, 8, 3, 1, 2, 5, 4, 7, 6, 10]>>> a.insert(5,1)>>> a[9, 8, 3, 1, 2, 1, 5, 4, 7, 6, 10]>>> a.remove(1)>>> a[9, 8, 3, 2, 1, 5, 4, 7, 6, 10]>>> a.pop(0)9>>> a[8, 3, 2, 1, 5, 4, 7, 6, 10]>>> a.pop()10>>> a[8, 3, 2, 1, 5, 4, 7, 6]>>> a.index(1)3>>> a.insert(2,6)>>> a[8, 3, 6, 2, 1, 5, 4, 7, 6] >>> a.count(3)1>>> a.count(6)2>>> a.sort()>>> a[1, 2, 3, 4, 5, 6, 6, 7, 8]>>> a.reverse()>>> a[8, 7, 6, 6, 5, 4, 3, 2, 1]>>>
1.2 將List當作棧(Stack)
使用上面將的 append, pop 函數很容易將List當作棧來使用。棧有先進後出的特點。
>>> stack = [5,2,8]>>> stack.append(9)>>> stack[5, 2, 8, 9]>>> stack.append(1)>>> stack[5, 2, 8, 9, 1]>>> stack.pop()1>>> stack[5, 2, 8, 9]>>> stack.pop()9>>> stack[5, 2, 8]
1.3 將List當作隊列
List同樣很容易當作隊列來使用,隊列的特點是先進先出。然而,這樣使用效率非常低。因為在隊列頭部刪除元素時, 所有後面的元素都要左移。 可以使用collections.deque來實現隊列,它是專門用於隊列的,其設計保證了入隊和出隊的效率。
>>> from collections import deque>>> queue = deque(["Linux","Unix","Windows"])>>> queuedeque(['Linux', 'Unix', 'Windows'])>>> queue.append("Mac")>>> queuedeque(['Linux', 'Unix', 'Windows', 'Mac'])>>> queue.popleft()'Linux'>>> queuedeque(['Unix', 'Windows', 'Mac'])
1.4 函數式程式設計工具
對於List來說,有三個函數是非常有用的:filter,map,reduce filter(function,sequence) 從序列中選出能使函數function返回真的元素
>>> def f(x): return x % 2 !=0 and x % 3 != 0... >>> filter(f, range(1,20))[1, 5, 7, 11, 13, 17, 19]
map(function,sequence) 將函數function作用到sequence上的每一個元素,返回對應的值
>>> def f(x): return x*2+1... >>> map(f,range(1,10))[3, 5, 7, 9, 11, 13, 15, 17, 19]
如果函數有兩個參數,那麼需要兩個序列
>>> def f(x,y): return x + y... >>> map(f,[1,5,2],[6,3,9])[7, 8, 11]
reduce(function,sequence) 將二元函數function作用在sequence前兩個元素上,再將結果和下一個元素共同作為函數參數
>>> def f (x,y): return x + y... >>> reduce(f,[1,2,3,4])10>>> def f(x,y): return x*y... >>> reduce(f,[1,2,3,4])24
1.5 List Comprehensions
List Comprehensions 是建立List的一種方式,例如
>>> squares = [x**2 for x in [4,3,7]]>>> squares[16, 9, 49]>>> [(x,y) for x in [1,2,3] for y in [3,2,4] if x != y][(1, 3), (1, 2), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
這種方式有時候可以避免寫很多代碼,而且清晰可讀,和數學裡定義集合的方式很像,haskell中也有這樣的方式。 另外,這貨還可以嵌套著玩兒
>>> matrix = [... [1,2,3,4],... [5,6,7],... [8,9,10,11,12]... ]>>> matrix[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12]]>>> [ [row[i] for row in matrix] for i in range(3) ][[1, 5, 8], [2, 6, 9], [3, 7, 10]]
當然,這隻是體現List Comprehensions的特性,真玩的時候,我們還有更方便的:
>>> zip(*matrix)[(1, 5, 8), (2, 6, 9), (3, 7, 10)]
2 del 語句
>>> a = [5,2,67,1,72,1,728]>>> a[5, 2, 67, 1, 72, 1, 728]>>> del a[0]>>> a[2, 67, 1, 72, 1, 728]>>> del a[1:3]>>> a[2, 72, 1, 728]>>> del a[:]>>> a[]>>> del a>>> aTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'a' is not defined
3 Tuples 和 序列
表示序列的,還有一種標準的資料結構,Tuples。 Tuple中的元素是不能修改的。 雖然Tuple和List看起來很像,但是他們用於不同的場合,後面我們會介紹。
>>> t = "linux", "unix", "winx">>> t('linux', 'unix', 'winx')>>> p = ("ubuntu","arch","freebsd")>>> p('ubuntu', 'arch', 'freebsd')>>> t[0]'linux'>>> t[0] = "*nix"Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>> s = [1,2,3]>>> s[1, 2, 3]>>> s[0] = 9>>> s[9, 2, 3]
Tuple 有packing 和 unpacking 兩個概念 packing 就是:
>>> t = "linux","unix","freebsd"
unpacking 就是:
>>> x, y, z = t>>> x'linux'>>> y'unix'>>> z'freebsd'
4 Sets
python還有一種資料結構,Sets。用於存放不重複元素的無序集合,常用於成員測試,消除重複項等。Sets支援 數學集合中的交,差,並,等操作。
>>> os = ['linux','windows7','freebsd']>>> oset = set(os)>>> osetset(['windows7', 'freebsd', 'linux'])>>> 'linux' in osetTrue>>> 'unix' in osetFalse>>> a = set('sdkf;ahdf')>>> b = set('safj13325er')>>> a - b # 在 a 不在 bset(['h', 'k', 'd', ';'])>>> a | b # 在 a 或在 bset(['r', 'a', 'e', 'd', 'f', 'h', 'k', 'j', '3', '1', 's', '2', '5', ';'])>>> a & b # 在 a 且在 bset(['a', 's', 'f'])>>> a ^ b # 在 a 或在 b 且不同時在a,bset(['e', 'd', 'h', 'k', 'j', '1', '3', '2', '5', ';', 'r'])
集合也支援 comprehensions 特性
>>> a = {x for x in 'abcde' if x not in 'abe'}>>> aset(['c', 'd'])
但是,必須要注意,定義一個sets時不能用{},而要用set() 5 Dictionaries
Python中另一個有用的資料結構是Dictionary。它由key:value兩部分組成,通過key值可以尋找到value,key值是惟一的。
>>> tel = {'jack':123, 'lucy':456}>>> tel['lucy']456>>> tel{'jack': 123, 'lucy': 456}>>> tel['lily'] = 789>>> tel{'lily': 789, 'jack': 123, 'lucy': 456}>>> tel.keys()['lily', 'jack', 'lucy']>>> 'lily' in telTrue
使用dict可以由(key,value)組成的序列直接構造dictionary. 使用comprehension的方式也可以構造dictionary.
>>> dict( [('linux',123),('unix',456)] ){'unix': 456, 'linux': 123}>>> dict(linux=826, unix=910){'unix': 910, 'linux': 826}>>> {x: x*2+1 for x in (3,7,1)}{1: 3, 3: 7, 7: 15}
6 迴圈技術
當我們想遍曆一個序列時,可以使用 下標,值,enumerate() 來完成
>>> for i, v in enumerate(['linux', 'unix', 'winx']):... print i, v... 0 linux1 unix2 winx
當我們想遍曆兩個及以上序列時,可以用 zip() 來完成
>>> ask = ['name', 'system', 'editor']>>> answer = ['Steve', 'Mac', 'emacs']>>> for q, a in zip(ask, answer):... print 'What is your {0}? It is {1}.'.format(q,a)... What is your name? It is Steve.What is your system? It is Mac.What is your editor? It is emacs.
如果想逆序遍曆,可以用 reversed() 來完成
>>> for i in reversed(['winx', 'unix', 'linux']):... print i... linuxunixwinx
如果想排序後再遍曆,可以用 sorted() 來完成
>>> for i in sorted( ['unix', 'linux', 'winx'] ):... print i... linuxunixwinx
如果想遍曆一個dictionary,可以用iteritems()來完成
>>> system = { 'unix':'second', 'linux':'first', 'winx':'last' }>>> for key,value in system.iteritems():... print key, value... unix secondwinx lastlinux first
7 更多的條件操作
對於 while 和 if 而言,條件操作不僅僅是比較,還有更多可用操作。 in 和 not in 可以判斷一個元素是否在一個序列中 is 和 not is 可以判斷兩個對象是不是指的是同一個對象 比較操作可以連結起來,例如 a < b == c , 表示 a < b 且 b == c 還有著名Bool操作: and, or, not ,它們可以配合比較操作 Bool操作優先順序低於比較操作,其中not優先順序最高,or最低 8 比較序列操作
序列對象也可以比較,它們是按照 字典序(lexicographical ordering) 的順序比較
>>> (1,2,3) < (1,2,4)True>>> (1,2,3,4) < (1,2,3)False>>> (1,2,3,-1) < (1,2,3)False>>> (1,2,3) == (1.0,2.0,3.0)True
原文連結:http://docs.python.org/2/tutorial/datastructures.html