2011年10月11日 星期二

[Learning Python] Collection Data Type -- Tuple(元組)

A. Tuple

    1. Tuple 是個可以將不同資料型別的 Object  Reference 放到一個單一序列的集合,而 Tuple 一旦被建立其內容就無法被改變。

    2. 建立 Tuple 的語法如下,

(Item1 , Item2 , Item3,....)                             




tupleName = (Item1 , Item2 , Item3,....)                             



    3. 可以用索引的方式取用 Tuple 中的元素

定義Tuple
>>> demoTuple=(1,2,3,'a','B','Ayana','satomi')                                         

印出整個Tuple
>>> print demoTuple
(1, 2, 3, 'a', 'B', 'Ayana', 'satomi')

印出第二個元素
>>> print demoTuple[1]
2

印出最後一個元素
>>> print demoTuple[-1]         
satomi
>>>
                 


















     4. 與其他 Object 合併結合成為新的 Tuple

定義整數物件
>>> x=123

定義另一個 Tuple
>>> otherTuple=(1,2,3,4)

合併
>>> demoTuple+(x,otherTuple)
(1, 2, 3, 'a', 'B', 'Ayana', 'satomi', 123, (1, 2, 3, 4))                                                     











    5. 要變更 Tuple 的資料項有兩個方法

        a. list()

        b. Temp Tuple 

    6. tupleName.count(Target)

        計算 Target 在 Tuple 中出現的次數。

    7.  tupleName.index(Target)

        回傳 Target 在  Tuple 中首次出現的位置,若 Target 不存在於 Tuple 中則拋出『ValueError』Exception。

   8. Tuple 可使用的運算 :
            a. concatenation : 『+』。
            b.replication :『*』。
            c. slice : 『[]』。
           d. membership operation : 『in』、『not in』。
          e. augmented assignment operation : 『+=』、『-=』。
          f. binary comparison operation : 『<』、『<=』、『==』、『!=』、『>=』、『>』。



    
Powered By Blogger