資料結構
一.簡介
資料結構基本上就是——它們是可以處理一些資料的結構。或者說,它們是用來儲存一組相關資料的。
在Python中有三種內建的資料結構——列表、元組和字典。我們將會學習如何使用它們,以及它們如何使編程變得簡單。
二.列表
list是處理一組有序項目的資料結構,即你可以在一個列表中儲存一個序列的項目。
一旦你建立了一個列表,你可以添加、刪除或是搜尋列表中的項目。由於你可以增加或刪除項目,我們說列表是可變的資料類型,即這種類型是可以被改變的。在某種程度上,與數組類似。
例如:
#!/usr/bin/python<br /># Filename: using_list.py</p><p># This is my shopping list<br />shoplist = ['apple', 'mango', 'carrot', 'banana']</p><p>print 'I have', len(shoplist),'items to purchase.'</p><p>print 'These items are:', # Notice the comma at end of the line<br />for item in shoplist:<br /> print item,</p><p>print '\nI also have to buy rice.'<br />shoplist.append('rice')<br />print 'My shopping list is now', shoplist</p><p>print 'I will sort my list now'<br />shoplist.sort()<br />print 'Sorted shopping list is', shoplist</p><p>print 'The first item I will buy is', shoplist[0]<br />olditem = shoplist[0]<br />del shoplist[0]<br />print 'I bought the', olditem<br />print 'My shopping list is now', shoplist </p><p>
輸出為:
$ python using_list.py<br />I have 4 items to purchase.<br />These items are: apple mango carrot banana<br />I also have to buy rice.<br />My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']<br />I will sort my list now<br />Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']<br />The first item I will buy is apple<br />I bought the apple<br />My shopping list is now ['banana', 'carrot', 'mango', 'rice'] </p><p>
三.元組
元組和列表十分類似,只不過元組和字串一樣是不可變的即你不能修改元組。元組通過圓括弧中用逗號分割的項目定義。元組通常用在使語句或使用者定義的函數能夠安全地採用一組值的時候,即被使用的元組的值不會改變。
四.字典
字典類似於你通過連絡人名字尋找地址和連絡人詳細情況的地址簿,即,我們把鍵(名字)和值(詳細情況)聯絡在一起。注意,鍵必須是唯一的。
注意,你只能使用不可變的對象(比如字串)來作為字典的鍵,但是你可以不可變或可變的對象作為字典的值。基本說來就是,你應該只使用簡單的對象作為鍵。
索引值對在字典中以這樣的方式標記:d = {key1 : value1, key2 : value2 }
。注意它們的鍵/值對用冒號分割,而各個對用逗號分割,所有這些都包括在花括弧中。
注意:字典中的鍵/值對是沒有順序的。如果你想要一個特定的順序,那麼你應該在使用前自己對它們排序。
例如:
#!/usr/bin/python<br /># Filename: using_dict.py</p><p># 'ab' is short for 'a'ddress'b'ook</p><p>ab = { 'Swaroop' : 'swaroopch@byteofpython.info',<br /> 'Larry' : 'larry@wall.org',<br /> 'Matsumoto' : 'matz@ruby-lang.org',<br /> 'Spammer' : 'spammer@hotmail.com'<br /> }</p><p>print "Swaroop's address is %s" % ab['Swaroop']</p><p># Adding a key/value pair<br />ab['Guido'] = 'guido@python.org'</p><p># Deleting a key/value pair<br />del ab['Spammer']</p><p>print '\nThere are %d contacts in the address-book\n' % len(ab)<br />for name, address in ab.items():<br /> print 'Contact %s at %s' % (name, address)</p><p>if 'Guido' in ab: # OR ab.has_key('Guido')<br /> print "\nGuido's address is %s" % ab['Guido']
五.序列
列表、元組和字串都是序列。序列的兩個主要特點是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個特定項目。切片操作符讓我們能夠擷取序列的一個切片,即一部分序列。
例如:
#!/usr/bin/python<br /># Filename: seq.py</p><p>shoplist = ['apple', 'mango', 'carrot', 'banana']</p><p># Indexing or 'Subscription' operation<br />print 'Item 0 is', shoplist[0]<br />print 'Item 1 is', shoplist[1]<br />print 'Item 2 is', shoplist[2]<br />print 'Item 3 is', shoplist[3]<br />print 'Item -1 is', shoplist[-1]<br />print 'Item -2 is', shoplist[-2]</p><p># Slicing on a list<br />print 'Item 1 to 3 is', shoplist[1:3]<br />print 'Item 2 to end is', shoplist[2:]<br />print 'Item 1 to -1 is', shoplist[1:-1]<br />print 'Item start to end is', shoplist[:]</p><p># Slicing on a string<br />name = 'swaroop'<br />print 'characters 1 to 3 is', name[1:3]<br />print 'characters 2 to end is', name[2:]<br />print 'characters 1 to -1 is', name[1:-1]<br />print 'characters start to end is', name[:] </p><p>
輸出為:
$ python seq.py<br />Item 0 is apple<br />Item 1 is mango<br />Item 2 is carrot<br />Item 3 is banana<br />Item -1 is banana<br />Item -2 is carrot<br />Item 1 to 3 is ['mango', 'carrot']<br />Item 2 to end is ['carrot', 'banana']<br />Item 1 to -1 is ['mango', 'carrot']<br />Item start to end is ['apple', 'mango', 'carrot', 'banana']<br />characters 1 to 3 is wa<br />characters 2 to end is aroop<br />characters 1 to -1 is waroo<br />characters start to end is swaroop </p><p>
切片操作符是序列名後跟一個方括弧,方括弧中有一對可選的數字,並用冒號分割。注意這與你使用的索引操作符十分相似。記住數是可選的,而冒號是必須的。
shoplist[1:3]
返回從位置1開始,包括位置2,但是停止在位置3的一個序列切片,因此返回一個含有兩個項目的切片。類似地,shoplist[:]
返回整個序列的拷貝。
六.參考
當你建立一個對象並給它賦一個變數的時候,這個變數僅僅參考那個對象,而不是表示這個對象本身。也就是說,變數名指向你電腦中儲存那個對象的記憶體。這被稱作名稱到對象的綁定。
例如:
#!/usr/bin/python<br /># Filename: reference.py</p><p>print 'Simple Assignment'<br />shoplist = ['apple', 'mango', 'carrot', 'banana']<br />mylist = shoplist # mylist is just another name pointing to the same object!</p><p>del shoplist[0]</p><p>print 'shoplist is', shoplist<br />print 'mylist is', mylist<br /># notice that both shoplist and mylist both print the same list without<br /># the 'apple' confirming that they point to the same object</p><p>print 'Copy by making a full slice'<br />mylist = shoplist[:] # make a copy by doing a full slice<br />del mylist[0] # remove first item</p><p>print 'shoplist is', shoplist<br />print 'mylist is', mylist<br /># notice that now the two lists are different </p><p>
輸出為:
$ python reference.py<br />Simple Assignment<br />shoplist is ['mango', 'carrot', 'banana']<br />mylist is ['mango', 'carrot', 'banana']<br />Copy by making a full slice<br />shoplist is ['mango', 'carrot', 'banana']<br />mylist is ['carrot', 'banana'] </p><p>
在某種程度上,類似於C中的指標。
七.一些關於字串的補充
你在程式中使用的字串都是str
類的對象。這個類的一些有用的方法會在下面這個例子中說明。如果要瞭解這些方法的完整列表,請參見help(str)
。
例如:
#!/usr/bin/python<br /># Filename: str_methods.py</p><p>name = 'Swaroop' # This is a string object </p><p>if name.startswith('Swa'):<br /> print 'Yes, the string starts with "Swa"'</p><p>if 'a' in name:<br /> print 'Yes, it contains the string "a"'</p><p>if name.find('war') != -1:<br /> print 'Yes, it contains the string "war"'</p><p>delimiter = '_*_'<br />mylist = ['Brazil', 'Russia', 'India', 'China']<br />print delimiter.join(mylist) </p><p>
輸出為:
$ python str_methods.py<br />Yes, the string starts with "Swa"<br />Yes, it contains the string "a"<br />Yes, it contains the string "war"<br />Brazil_*_Russia_*_India_*_China </p><p>
#!/usr/bin/python<br /># Filename: using_tuple.py</p><p>zoo = ('wolf', 'elephant', 'penguin')<br />print 'Number of animals in the zoo is', len(zoo)</p><p>new_zoo = ('monkey', 'dolphin', zoo)<br />print 'Number of animals in the new zoo is', len(new_zoo)<br />print 'All animals in new zoo are', new_zoo<br />print 'Animals brought from old zoo are', new_zoo[2]<br />print 'Last animal brought from old zoo is', new_zoo[2][2] </p><p>
輸出為:
$ python using_tuple.py<br />Number of animals in the zoo is 3<br />Number of animals in the new zoo is 3<br />All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))<br />Animals brought from old zoo are ('wolf', 'elephant', 'penguin')<br />Last animal brought from old zoo is penguin </p><p>
變數zoo
是一個元組,我們看到len
函數可以用來擷取元組的長度。這也表明元組也是一個序列。
含有0個或1個項目的元組。一個空的元組由一對空的圓括弧組成,如myempty = ()
。然而,含有單個元素的元組就不那麼簡單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣Python才能區分元組和運算式中一個帶圓括弧的對象。即如果你想要的是一個包含項目2
的元組的時候,你應該指明singleton = (2 , )
。
例如:
#!/usr/bin/python<br /># Filename: print_tuple.py</p><p>age = 22<br />name = 'Swaroop'</p><p>print '%s is %d years old' % (name, age)<br />print 'Why is %s playing with that python?' % name </p><p>
輸出為:
$ python print_tuple.py<br />Swaroop is 22 years old<br />Why is Swaroop playing with that python? </p><p>