1. 程式人生 > >python之tuple

python之tuple

無符號 enter 不同 元組 idt 出現的次數 cmp 修改 方法

1、python元組

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

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

#創建元組
>>> tuple2 = 123,456,hello‘  #任意無符號的對象,以逗號隔開,默認為元組
>>> type(tuple2)
<class tuple>
>>> tuple1 = (a,b,c)
>>> type(tuple1)
<class tuple>

>>> tuple3 = ()   #創建空元組

>>> tuple4 = (10)
>>> type(tuple4) <class int> >>> tuple4 = (10,) #在創建元組中只包含一個元素時,需要在元素後面添加逗號 >>> type(tuple4) <class tuple>

2、訪問元組,組合元組,刪除元組

#訪問元組與訪問列表一樣,使用下標索引來訪問元組中的值
>>> tup1 = (number,string,list,tuple,dictionary)
>>> tup1[:]
(number, string
, list, tuple, dictionary) >>> tup1[3] tuple >>> tup1[1:4] (string, list, tuple) #鏈接組合元組 >>> tup2 = (1,2,3,4,5) >>> tup3 = tup1+tup2 >>> tup3 (number, string, list, tuple, dictionary, 1, 2, 3, 4, 5) #刪除元組,使用del語句來刪除整個元組 >>> del
tup3

3、元組運算符

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

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 叠代

4、元組內置函數與方法

In [14]: tup1 = (1,2,3)     #創建元組 
In [15]: tup2 = (a,b,c)

In [16]: cmp(tup1,tup2)   #比較元組
Out[16]: -1
In [17]: cmp(tup2,tup1)
Out[17]: 1

In [18]: len(tup1)  #統計元組元素個數
Out[18]: 3

In [19]: max(tup1)  #返回元組元素最大值
Out[19]: 3
In [20]: max(tup2)
Out[20]: c

In [21]: min(tup2)  #返回元組元素最小值
Out[21]: a

In [22]: list1 = [33,22,11]
In [23]: tuple(list1)     #將列表轉換成元組
Out[23]: (33, 22, 11)

In [24]: tup2.count(a)    #統計元組中元素出現的次數
Out[24]: 1

In [25]: tup2.index(a)   #顯示元組中元素的索引
Out[25]: 0
In [26]: tup2.index(c)
Out[26]: 2

python之tuple