python-tuple詳解


python - 元組

Python的元組與列表類似,不同之處在於元組的元素不能修改。

元組使用小括號,列表使用方括號。

元組創建很簡單,只需要在括號中添加元素,並使用逗號隔開即可。

  • 創建元組
>>> tup1 = ('fd',123) >>> tup2 = () >>> tup1 ('fd', 123) >>> tup2 ()    

 

無關閉分隔符

任意無符號的對象,以逗號隔開,默認為元組

>>> tup7 = 13,3,'yuanzu' >>> tup7 (13, 3, 'yuanzu')

 

 

  • 訪問元組

元組可以使用下標索引來訪問元組中的值,如下實例:

>>> tup5 = ('23','mayun','dongzuo','mahuateng') >>> tup5[1] 'mayun' >>> tup5[1:3] ('mayun', 'dongzuo')

 

 

  • 修改:不可以修改,但是兩個元組可以連接生成一個新元組
>>> tup3 ('wangjinlin', 'lijiacheng') >>> tup5 ('23', 'mayun', 'dongzuo', 'mahuateng') >>> tup6 = tup3 +tup5 >>> tup6 ('wangjinlin', 'lijiacheng', '23', 'mayun', 'dongzuo', 'mahuateng')
  • 刪除:元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組

>>> tup6 ('wangjinlin', 'lijiacheng', '23', 'mayun', 'dongzuo', 'mahuateng') >>> del tup6 >>> tup6 Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'tup6' is not defined

 

 

  • 元組運算符

與字符串一樣,元組之間可以使用 + 號和 * 號進行運算。這就意味着他們可以組合和復制,運算后會生成一個新的元組。

Python 表達式 結果 描述
len((1, 2, 3)) 3 計算元素個數
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 連接
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 復制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print x, 1 2 3 迭代

 

 

 

 

 

 

 

 

  • 元組內置函數Python元組包含了以下內置函數(與list差不多的函數)

1、cmp(tuple1, tuple2):比較兩個元組元素。
2、len(tuple):計算元組元素個數。
3、max(tuple):返回元組中元素最大值。
4、min(tuple):返回元組中元素最小值。
5、tuple(seq):將列表轉換為元組。

  •  元組的方法

1.T.count(value) -> integer -- return number of occurrences of value

返回元組中包含指定元素的個數

>>> tup1 = (12,'mayuan','dongdong','xixi','mayuan') >>> tup1.count('mayuan') 2 >>> tup1.count('m') 0

 

2.T.index(value, [start, [stop]]) -> integer -- return first index of value

 返回指定元素的第一個匹配的索引值

 

>>> tup1 (12, 'mayuan', 'dongdong', 'xixi', 'mayuan') >>> tup1.index('mayuan') 1 >>> tup1.index('mayuan',2,5) 4 >>> tup1.index('sb') #如果元組中不包含指定的元素,就報valueerror Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: tuple.index(x): x not in tuple

 

 

 

end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM