簡介
tuple
1.元組是以圓括號“()”包圍的數據集合,不同成員以“,”分隔。通過下標進行訪問
2.不可變序列,可以看做不可變的列表,與列表不同:元組中數據一旦確立就不能改變(所以沒有類似列表的增刪改操作,只有基本序列操作)
3.支持任意類型,任意嵌套以及常見的序列操作
4.元組通常用在使語句或用戶定義的函數能夠安全地采用一組值的時候,即被使用的元組的值不會改變
聲明及使用
代碼如下:
t = () #空元組
t =(1,) #單個元素元組,注意逗號必須
t =(1,2,3)
1 in t #判斷
2 not in t
#其他同序列基本操作:分片,索引
print t[0]
print t[-1]
print t[:2]
#不會對原來元組造成影響
print t+(4,5) #返回新元組(1,2,3,4,5)
print t * 2 #(1,2,3,1,2,3)
t.index(1)
t.count(1)
#列表元組轉換
l = [1,2,3]
lt = tuple(l)
tl = list(lt)
lt_sorted = sorted(l) #對元組進行排序,返回是列表
#字符串轉元組(得到字符元組序列)
print tuple('hello) #('h','e','l','l','o')
tuple沒有append/extend/remove/pop等增刪改操作tuple沒有find
查看幫助
代碼如下:
help(tuple)
用途
1.賦值
代碼如下:
t = 1,2,3 #等價 t = (1, 2, 3)
x, y, z = t #序列拆封,要求左側變量數目和右側序列長度相等
2.函數多個返回值
代碼如下:
def test():
return (1,2)
x, y = test()
3.傳參[強制不改變原始序列]
代碼如下:
def print_list(l):
t = tuple(l) #或者t = l[:]
dosomething()
4.字符串格式化
代碼如下:
print '%s is %s years old' % ('tom', 20)
5.作為字典的key
優點
1.性能
tuple比列表操作速度快
若需要定義一個常量集,或者是只讀序列,唯一的操作是不斷遍歷之,使用tuple代替list
代碼如下:
>>> a = tuple(range(1000))
>>> b = range(1000)
>>> def test_t():
... for i in a:
... pass
...
>>> def test_l():
... for i in b:
... pass
...
>>> from timeit import Timer
>>> at = Timer("test_t()", "from __main__ import test_t")
>>> bt = Timer("test_l()", "from __main__ import test_l")
簡單測試
代碼如下:
>>> at.repeat(3, 100000)
[1.526214838027954, 1.5191287994384766, 1.5181210041046143]
>>> bt.repeat(3, 100000)
[1.5545141696929932, 1.557785987854004, 1.5511009693145752]
2.不可變性
新聞熱點
疑難解答