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