Python學習--數據結構

數據結構

 

        數據結構基本上就是:可以處理一些數據的結構 。或者說,是用來存儲一組相關數據的。在Python中有三種內建的數據結構:列表、元組和字典。

  • 列表

        list是處理一組有序項目的數據結構,即你可以在一個列表中存儲一個序列的項目。
        注意:1)在Python中,你在每個項目之間用逗號分割。
                   2)列表中的項目應該包括在方括號中,這樣Python就知道你是在指明一個列表。
                   3)一旦你創建了一個列表,你可以添加、刪除或是搜索列表中的項目。
                   4)列表是可變的數據類型,即這種類型是可以被改變的。
        下面的例子介紹如何使用列表

shoplist = [ 'apple' , 'mango' , 'carrot' , 'banana' ]
print 'I have' , len (shoplist), 'items to purchase.'
print 'These items are:' , 
for item in shoplist:
    print item
print '\nI also have to buy rice.'
shoplist.append( 'rice' )
print 'My shopping list is now' ,shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is' ,shoplist
print 'The first item I will buy is' , shoplist[ 0 ]
olditem = shoplist[ 0 ]
del shoplist[ 0 ]
print 'I bought the' , olditem
print 'My shopping list is now' ,shoplist

        輸出

I have 4 items to purchase.
These items are: apple
mango
carrot
banana

I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

        變量shoplist是某人的購物列表。 在shoplist中,我們只存儲購買的東西的名字字符串,但是你可以在列表中添加任何種類的對象包括數甚至其他列表。

        接下來,我們使用append方法在列表中添加了一個項目。然後我們通過打印列表的內容來檢驗這個項目是否確實被添加進列表了。打印列表只需簡單地把列表傳遞給print語句,我們可以得到一個整潔的輸出。
        再接下來,我們使用列表的sort方法來對列表排序。需要理解的是,這個方法影響列表本身,而不是返回一個修改後的列表,這與字符串工作的方法不同。這就是我們所說的列表是可變的而字符串是不可變的。
        最後,我們想要把它從列表中刪除。我們使用del語句來完成這個工作。這裏,我們指出我們想要刪除列表中的哪個項目,而del語句爲我們從列表中刪除它。我們指明我們想要刪除列表中的第一個元素,因此我們使用del shoplist[0](記住,Python從0開始計數)。

        注意:我們在print語句的結尾使用了一個逗號來消除每個print語句自動打印的換行符。這樣做有點難看,不過確實簡單有效。

 

  • 元組

        元組和列表十分類似,只不過元組和字符串一樣是不可變的即你不能修改元組。元組通過圓括號中用逗號分割的項目定義。元組通常用在使語句或用戶定義的函數能夠安全地採用一組值的時候,即被使用的元組的值不會改變。
        下面的例子介紹如何使用元組

zoo = ( 'wolf' , 'elephant' , 'penguin' )
print 'Number of animals in the zoo is' , len (zoo) 
new_zoo = ( 'monkey' , 'dolphin' ,zoo)
print 'Number of animals in the new zoo is' , len (new_zoo)
print 'All animals in new zoo are' , new_zoo
print 'Animals brought from old zoo are' , new_zoo[ 2 ]
print 'Last animal brought from old zoo is' , new_zoo[ 2 ][ 2 ]
        輸出
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
        變量zoo是一個元組,我們看到len函數可以用來獲取元組的長度。這也表明元組也是一個序列。
        我們可以通過一對方括號來指明某個項目的位置從而來訪問元組中的項目,就像我們對列表的用法一樣。這被稱作索引運算符。我們使用new_zoo[2]來訪問new_zoo中的第三個項目。我們使用new_zoo[2][2]來訪問new_zoo元組的第三個項目的第三個項目。
        含有0個或1個項目的元組。一個空的元組由一對空的圓括號組成,myempty = ()。然而,含有單個元素的元組就不那麼簡單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣Python才能區分元組和表達式中一個帶圓括號的對象。即如果你想要的是一個包含項目2的元組的時候,你應該指明singleton = (2 , )。
        注意:元組之內的元組不會失去它的身份。
        元組與打印語句
        元組最通常的用法是用在打印語句中,下面是一個例子:
age = 22
name = 'Swaroop'
print '%s is %d years old' % (name,age)
print 'Why is %s playing with that python?' % name
        輸出
Swaroop is 22 years old
Why is Swaroop playing with that python?
        print語句可以使用跟着%符號的項目元組的字符串。這些字符串具備定製的功能。定製讓輸出滿足某種特定的格式。元組必須按照相同的順序來對應這些定製。
        觀察我們使用的第一個元組,我們首先使用%s,這對應變量name,它是元組中的第一個項目。而第二個定製是%d,它對應元組的第二個項目age。
        Python在這裏所做的是把元組中的每個項目轉換成字符串並且用字符串的值替換定製的位置。因此%s被替換爲變量name的值,依此類推。print的這個用法使得編寫輸出變得極其簡單,它避免了許多字符串操作。它也避免了我們一直以來使用的逗號。
        在大多數時候,你可以只使用%s定製,而讓Python來提你處理剩餘的事情。這種方法對數同樣奏效。然而,你可能希望使用正確的定製,從而可以避免多一層的檢驗程序是否正確。
        在第二個print語句中,我們使用了一個定製,後面跟着%符號後的單個項。這隻在字符串中只有一個定製的時候有效。
        注意:定製可以是%s表示字符串或%d表示整數。
  • 字典
        字典類似於你通過聯繫人名字查找地址和聯繫人詳細情況的地址簿,即我們把鍵(名字)和值(詳細情況)聯繫在一起。
        鍵值對在字典中以這樣的方式標記:d = {key1 : value1, key2 : value2 }。
        字典是dict類的實例/對象。
        注意:1)鍵必須是唯一的。
                   2)你只能使用不可變的對象(比如字符串)來作爲字典的鍵,但是你可以把不可變或可變的對象作爲字典的值。基本說來就是,你應該只使用簡單的對象作爲鍵。
                   3)字典中的鍵/值對用冒號分割,而各個對用逗號分割,所有這些都包括在花括號中。
                   4)字典中的鍵/值對是沒有順序的。如果你想要一個特定的順序,那麼你應該在使用前自己對它們排序。
        下面的例子介紹如何使用字典
ab = { 'Swaroop' : '[email protected]' ,'Larry' : '[email protected]' ,'Matsumoto' : '[email protected]' ,'Spammer' : '[email protected]'}
print "Swaroop's address is %s" %ab[ 'Swaroop' ]
ab[ 'Guido' ] = '[email protected]'
del ab[ 'Spammer' ]
print '\nThere are %d contacts in the address-book\n' % len (ab)
for name, address in ab.items():
    print 'Contact %s at %s' %(name, address)
if 'Guido' in ab:
    ab.has_key('Guido')
    print "\nGuido's address is %s" % ab[ 'Guido' ]
         輸出
Swaroop's address is [email protected]

There are 4 contacts in the address-book

Contact Swaroop at [email protected]
Contact Matsumoto at [email protected]
Contact Larry at [email protected]
Contact Guido at [email protected]

Guido's address is [email protected]
         我們使用標記創建了字典ab,然後使用在列表和元組章節中已經討論過的索引操作符來指定鍵,從而使用鍵/值對。
        我們可以使用索引操作符來尋址一個鍵併爲它賦值,這樣就增加了一個新的鍵/值對,就像在上面的例子中我們對Guido所做的一樣。
        我們可以使用del語句來刪除鍵/值對。我們只需要指明字典和用索引操作符指明要刪除的鍵,然後把它們傳遞給del語句就可以了。執行這個操作的時候,我們無需知道那個鍵所對應的值。
        接下來,我們使用字典的items方法,來使用字典中的每個鍵/值對。這會返回一個元組的列表,其中每個元組都包含一對項目,鍵與對應的值。我們抓取這個對,然後分別賦給for..in循環中的變量name和address然後在for-塊中打印這些值。
        我們可以使用in操作符來檢驗一個鍵/值對是否存在,或者使用dict類的has_key方法。你可以使用help(dict)來查看dict類的完整方法列表。

  • 序列
        列表、元組和字符串都是序列。序列的兩個主要特點:索引操作符和切片操作符。
        索引操作符讓我們可以從序列中抓取一個特定項目。
        切片操作符讓我們能夠獲取序列的一個切片,即一部分序列。
        下面的例子介紹如何使用序列
shoplist =[ 'apple' , 'mango' , 'carrot' , 'banana' ]

print 'Item 0 is' , shoplist[ 0 ]
print 'Item 1 is' , shoplist[ 1 ]
print 'Item 2 is' , shoplist[ 2 ]
print 'Item 3 is' , shoplist[ 3 ]
print 'Item -1 is' , shoplist[ -1 ]
print 'Item -2 is' , shoplist[ -2 ]
print 'Item 1 to 3 is' ,shoplist[ 1 : 3 ]
print 'Item 2 to end is' ,shoplist[ 2 :]
print 'Item 1 to -1 is' ,shoplist[ 1 : -1 ]
print 'Item start to end is' ,shoplist[:]

name = 'swaroop'
print 'characters 1 to 3 is' ,name[ 1 : 3 ]
print 'characters 2 to end is' ,name[ 2 :]
print 'characters 1 to -1 is' ,name[ 1 : -1 ]
print 'characters start to end is' ,name[:]
        輸出
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
         首先,我們來學習如何使用索引來取得序列中的單個項目。這也被稱作是下標操作。每當你用方括號中的一個數來指定一個序列的時候,Python會爲你抓取序列中對應位置的項目。記住,Python從0開始計數。因此,shoplist[0]抓取第一個項目,shoplist[3]抓取shoplist序列中的第四個元素。索引同樣可以是負數,在那樣的情況下,位置是從序列尾開始計算的。因此,shoplist[-1]表示序列的最後一個元素而shoplist[-2]抓取序列的倒數第二個項目。
        切片操作符是序列名後跟一個方括號,方括號中有一對可選的數字,並用冒號分割。切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之後)表示切片到哪裏結束。如果不指定第一個數,Python就從序列首開始。如果沒有指定第二個數,則Python會停止在序列尾。shoplist[:]返回整個序列的拷貝。你可以用負數做切片。負數用在從序列尾開始計算的位置。shoplist[:-1]會返回除了最後一個項目外包含所有項目的序列切片。
        使用Python解釋器交互地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結果。序列的神奇之處在於你可以用相同的方法訪問元組、列表和字符串。
        注意:1)這與你使用的索引操作符十分相似。記住數是可選的,而冒號是必須的。
              2)返回的序列從開始位置開始 ,剛好在結束位置之前結束。即開始位置是包含在序列切片中的,而結束位置被排斥在切片外。

  • 引用
        當你創建一個對象並給它賦一個變量的時候,這個變量僅僅引用那個對象,而不是表示這個對象本身!也就是說,變量名指向你計算機中存儲那個對象的內存。這被稱作名稱到對象的綁定。
        一般說來,你不需要擔心這個,只是在引用上有些細微的效果需要你注意。這會通過下面這個例子加以說明。
print 'Simple Assignment'
shoplist =[ 'apple' , 'mango' , 'carrot' , 'banana' ]
mylist = shoplist
del shoplist[ 0 ]
print 'shoplist is' , shoplist
print 'mylist is' , mylist

print 'Copy by making a full slice'
mylist = shoplist[:]
del mylist[ 0 ]
print 'shoplist is' , shoplist
print 'mylist is' , mylist
        輸出
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
        如果你想要複製一個列表或者類似的列或者其他複雜的對象(不是如整數那樣的簡單對象),那麼你必須使用切片操作符來取得拷貝。
        如果你只是想要使用另一個變量名,兩個名稱都引用同一個對象,那麼如果你不小心的話,可能會引來各種麻煩。

  • 更多字符串的內容
        字符串也是對象,同樣具有方法。這些方法可以完成包括檢驗一部分字符串和去除空格在內的各種工作。我們在程序中使用的字符串都是str類的對象。這個類的一些有用的方法會在下面這個例子中說明。如果要了解這些方法的完整列表,請參見help(str)。
name = 'Swaroop'
if name.startswith( 'Swa' ):
    print 'Yes, the string starts with "Swa"'
if 'a' in name:
    print 'Yes, it contains the string "a"'
if name.find( 'war' ) != -1 :
    print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist =[ 'Brazil' , 'Russia' , 'India' , 'China' ]
print delimiter.join(mylist)
        輸出
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
         這裏,我們看到使用了許多字符串方法:
        startwith方法是用來測試字符串是否以給定字符串開始。
        in操作符用來檢驗一個給定字符串是否爲另一個字符串的一部分。
        find方法用來找出給定字符串在另一個字符串中的位置,或者返回-1以表示找不到子字符串。
        str類也有以一個作爲分隔符的字符串join序列的項目的整潔的方法,它返回一個生成的大字串。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章