python學習之路-第五天-python的資料結構

來源:互聯網
上載者:User

標籤:down   app   ati   字元   迴圈   檢驗   make   sorted   特殊   

資料結構1. 列表
  • 例子:
#!/usr/bin/python# Filename: using_list.py# This is my shopping listshoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]print ‘I have‘, len(shoplist),‘items to purchase.‘print ‘These items are:‘, # Notice the comma at end of the linefor item in shoplist:    print item,print ‘\nI also have to buy rice.‘shoplist.append(‘rice‘)print ‘My shopping list is now‘, shoplistprint ‘I will sort my list now‘shoplist.sort()print ‘Sorted shopping list is‘, shoplistprint ‘The first item I will buy is‘, shoplist[0]olditem = shoplist[0]del shoplist[0]print ‘I bought the‘, olditemprint ‘My shopping list is now‘, shoplist
  • 結果
$ python using_list.pyI have 4 items to purchase.These items are: apple mango carrot bananaI also have to buy rice.My shopping list is now [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘, ‘rice‘]I will sort my list nowSorted shopping list is [‘apple‘, ‘banana‘, ‘carrot‘, ‘mango‘, ‘rice‘]The first item I will buy is appleI bought the appleMy shopping list is now [‘banana‘, ‘carrot‘, ‘mango‘, ‘rice‘]
  • 列表中可以添加任意種類的對象

  • for in實現了列表的遍曆

  • append方法可以添加新的對象

  • sort方法可以對列表排序,是對列表本身的修改

  • del方法後面接上列表中的任意位置,可以刪除該對象

2. 元組
  • 元組和列表的形式差不多,不過元組中的對象是不允許修改的

  • 含有0或1個對象的元組比較特殊:一個空的元組由一對空的圓括弧組成,如myempty = ()。然而,含有單個元素的元組就不那麼簡單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣Python才能區分元組和運算式中一個帶圓括弧的對象。即如果你想要的是一個包含項目2的元組的時候,你應該指明singleton = (2 , )。

  • 元組通常用於列印語句:

  • 例子:

#!/usr/bin/python# Filename: print_tuple.pyage = 22name = ‘Swaroop‘print ‘%s is %d years old‘ % (name, age)print ‘Why is %s playing with that python?‘ % name
$ python print_tuple.pySwaroop is 22 years oldWhy is Swaroop playing with that python?
  • 與c中的列印語句類似,不過在python中不用逗號分隔,直接用%定製

  • 在第二個print語句中,我們使用了一個定製,後面跟著%符號後的單個項目——沒有圓括弧。這隻在字串中只有一個定製的時候有效。

3. 字典
  • 字典其實就是key-value對

  • 例子:

#!/usr/bin/python# Filename: using_dict.py# ‘ab‘ is short for ‘a‘ddress‘b‘ookab = {       ‘Swaroop‘   : ‘[email protected]‘,             ‘Larry‘     : ‘[email protected]‘,             ‘Matsumoto‘ : ‘[email protected]‘,             ‘Spammer‘   : ‘[email protected]‘     }print "Swaroop‘s address is %s" % ab[‘Swaroop‘]# Adding a key/value pairab[‘Guido‘] = ‘[email protected]‘# Deleting a key/value pairdel 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: # OR ab.has_key(‘Guido‘)    print "\nGuido‘s address is %s" % ab[‘Guido‘]
  • 結果:
$ python using_dict.pySwaroop‘s address is [email protected]There are 4 contacts in the address-bookContact 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]
  • items方法用於返回一個元組的列表,每個列表中都有鍵和值,如上面的for迴圈遍曆

  • in方法或者has_key方法可以檢驗這個鍵是否存在

序列

上面列表,元組,字典都是序列,都有序列的各種方法,序列就是包括索引操作和切片操作;

例子:

#!/usr/bin/python# Filename: seq.pyshoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]# Indexing or ‘Subscription‘ operationprint ‘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]# Slicing on a listprint ‘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[:]# Slicing on a stringname = ‘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[:]
$ python seq.pyItem 0 is appleItem 1 is mangoItem 2 is carrotItem 3 is bananaItem -1 is bananaItem -2 is carrotItem 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 wacharacters 2 to end is aroopcharacters 1 to -1 is waroocharacters start to end is swaroop
  • 索引不必多說,下標從0開始,-1表示從右向左數1個,(其實我記憶的話,序列的長度加上這個值,就是他的真實下標)

  • 切片符號‘:‘為標誌,包括第一個運算元,不包括第二個,也就是左閉右開

  • 左運算元為空白,從開始位置開始,右運算元為空白,到結束位置結束

參考

下面是個例子:

#!/usr/bin/python# Filename: reference.pyprint ‘Simple Assignment‘shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]mylist = shoplist # mylist is just another name pointing to the same object!del shoplist[0]print ‘shoplist is‘, shoplistprint ‘mylist is‘, mylist# notice that both shoplist and mylist both print the same list without# the ‘apple‘ confirming that they point to the same objectprint ‘Copy by making a full slice‘mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint ‘shoplist is‘, shoplistprint ‘mylist is‘, mylist# notice that now the two lists are different
$ python reference.pySimple Assignmentshoplist is [‘mango‘, ‘carrot‘, ‘banana‘]mylist is [‘mango‘, ‘carrot‘, ‘banana‘]Copy by making a full sliceshoplist is [‘mango‘, ‘carrot‘, ‘banana‘]mylist is [‘carrot‘, ‘banana‘]

從上面的注釋中我們已經能看出來,直接用=串連的賦值相當於直接拷貝的地址,原來序列改變,相應賦值的序列也會改變,但是賦值的時候用序列的切片操作賦值,改變原序列後不會影響到賦值的序列

python學習之路-第五天-python的資料結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.