集合型態

Python裡的集合主要分為三種:List, set & Dictionary.
set:無序的資料結構。集合之中的元素並沒有特定排序。
相對於set而有序的集合為List。List擁有特定的排列方式排列元素,這個比較接近其他程式語言的陣列。但是陣列無法改變大小,而List可以。
集合中還有一種叫做dictionary,Python中命名為dict。通常中文翻作為字典,是一種擁有Key與Value一對組合的物件。用法是將一組Key與value放入dict,並藉由key取出想要的value。

List的語法如下:

list = [object1,object2,object3,...]
>>>explist = [1,2,3,4]
>>>print explist
[1,2,3,4]

以下簡單運用的範例

explist = [1,2,3,4]
theStr = 'example'
 
#在後方加入5,6
explist.extend([5,6])
print explist
 
#至索引到4的位置替代為11,12,13,14,15
explist[:4] = [11,12,13,14,15]
print explist
 
#刪除倒數第1,2個
del explist[-2]
del explist[-1]
print explist
 
#順序倒過來
explist.reverse()
print explist
 
#變更為一個元素
explist = [explist,20,21,22]
print explist
#-----------result--------------
[1, 2, 3, 4, 5, 6]
[11, 12, 13, 14, 15, 5, 6]
[11, 12, 13, 14, 15]
[15, 14, 13, 12, 11]
[[15, 14, 13, 12, 11], 20, 21, 22]

Python之中還有一種Tuple物件,跟List很像。不過Tuple不能更改大小及元素。
除此之外Tuple能夠達成與List相同的功能。

>>> t = (1,2,5)
>>> for i in t:
...    print i ** 2
...
 
1
4
25
>>> l = [1,2,5]
>>> l.extend([3])
>>> l
[1, 2, 5, 3]
>>> t.extend((3))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    t.extend((3))
AttributeError: 'tuple' object has no attribute 'extend'