簡明Python教程 — 9.資料結構

來源:互聯網
上載者:User

簡明Python教程 --- 9.資料結構

 

相信資料結構這個東西,所有學過編程的人都不會陌生。這裡只介紹一下Python內建的3種資料結構:列表、元組、字典。

列表(list)

   list是用於處理一組有序對象的資料結構。

myList = ['a', 'b', 'c', 'd'];

for element in myList :

   print element;

Python中為list提供了一個方法append,可以往列表中添加對象。

myList.append('e');

注意,從list中刪除一個對象不是通過list中的方法來實現的。你必須使用del語句來從數組中刪除對象。

del myList[2];

你可以運行下面的程式來觀察上面提到的情況:

myList = ['a', 'b', 'c', 'd'];

for element in myList :

   print element;

print('------------------------');

myList.append('e');

for element in myList :

   print element;

print('------------------------');

del myList[2];

for element in myList :

   print element;

元組

   元組和列表是非常類似的。它們的不同點是元組不可修改。你無法向元組中添加對象,也無法從元組中刪除對象。

   元組的聲明也和列表有所不同,列表使用方括弧聲明,而元組則使用圓括弧來聲明。

   myTuple = ('a', 'b', 'c', 'd');

for element in myTuple :

      print element;

字典

   字典就像是通過人名來查詢人的聯絡資訊的通訊錄。如果你學過Java,那麼你一定知道Map,是的,Python中的字典和Java中的Map的功能是非常相似的。

   myDict = {'Tom':u'美國','ZhangQiang':u'中國'};

print myDict['ZhangQiang'];

序列

   列表、元組、字串都是序列,但什麼是序列嗎?序列的2個主要特點索引操作符和切片操作符。這裡僅僅舉一個例子來說明序列是什麼。

   shoplist = ['apple', 'mango', 'carrot', 'banana']

# Indexing or 'Subscription' operation

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]

# Slicing on a list

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[:]

# Slicing on a string

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[:]

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.