Python編程中數組、隊列及堆棧用於保存一組數據或對象的序列,元素可以是各種類型混合在一起,定義格式為[元素,元素,……,元素],用變量[位置]即可取出相應的元素,其中“位置”是從零開始計算。
數組表示一組序列集,元素可以在相應的位置存取。
# 例1:使用數組 array = [1,2,3,'hello',5] # 定義五個元素的數組 print array[0] # 輸出位置0元素 >> 1 pos = 3 print array[pos] # 輸出位置3元素 >> hello
隊列是一組以排隊的形式先進先出的序列集,定義方法和數組是一致的,使用的函數也均可在數組或堆棧中使用。
# 例2:使用隊列
alist = [1,2,3,4] # 建立隊列
alist.append[5] # 隊尾添加元素5
alist.append['hello'] # 添加元素hello
print len(alist) # 輸出隊列alist的長度
>> 6
alist.pop(0) # 彈出首元素 1
alist.remove('hello') # 移除元素'hello'
alist.insert(0,'Python') # 在位置0插入元素'Python'
print alist.index('Python') # 獲得元素'Python'所在的位置
>> 0
alist.sort() # 將alist順序排序
alist.sort(None,None,True) # 將alist倒序排序
alist.reverse() # 將alist翻轉
print alist
>> [2,3,4,5,'Python']
blist = [6,7,8]
alist.extend(blist) # 擴展隊列alist
print alist
>> 2,3,4,5,'Python',6,7,8 # 輸出結果
堆棧是一組指定義方式與定義數組隊列一致。
# 例3:使用堆棧 alist = [2,2,3,4,5] # 建立堆棧 alist.count(2) # 統計2的個數 >> 2 alist.append[6] # 壓入元素6 alist.pop() # 彈出元素6
http://www.17jo.com/program/python/base/ListUse.html
3.2入門教程:
http://docspy3zh.readthedocs.org/en/latest/tutorial/
