python 元組tuple

# -*- coding: utf8 -*-
"""
元組的相關測試, 基本和列表一模一樣,除了元素不能被修改,元組用小括號括起,實際起作用的是逗號
"""

#定義
#空元組
tuple1 = ()

#創建一個元素,和列表有所區別
tupleOne1 = ('hello',)
tupleOne2 = 'hello', #小括號可以不加,但最好加上
tupleOne3 = tuple(('hello',))
print(tupleOne1)  #('hello',)
print(tupleOne2)  #('hello',)
print(tupleOne3)  #('hello',)

#創建方式
tuple2 = ('a', 2.2, (1, 'b'), {'pi': 3.14}, 3e-2)
print(tuple2)  #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)

strTemp = 'hello'
tuple3 = tuple(strTemp)
print(tuple3)  #('h', 'e', 'l', 'l', 'o')
tuple333 = tuple(('hello',)) #注意傳入的是一個元組,此處可簡寫成tuple333 = ('hello',)
print(tuple333)  #('h', 'e', 'l', 'l', 'o')
strTemp = 'worlld'
print(tuple3)


list1 = [1, 'a', 3.3]
tuple4 = tuple(list1)
print(tuple4)  #(1, 'a', 3.3)

#修改元組元素,只能通過拼接的方法'修改'
#tuple4[1] = 'b'  #肯定報錯:TypeError: 'tuple' object does not support item assignment(元組不支持裏面的項被改變)
tuple4 = tuple4[:1] + ('new',) + tuple4[1:]  #注意要加逗號(1, 'new', 'a', 3.3)
print(tuple4)  #(1, 'a', 3.3)

#直接賦值不會創建新內存,只是等於這塊內存多了一個標籤
tuple5 = tuple2
print('t5=%d, t2=%d' % (id(tuple5), id(tuple2)))
print(tuple5)  #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
tuple2 = tuple2[:1] + tuple2[2]
print(tuple2)  #('a', 1, 'b')
print(tuple5)  #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)


#長度
tuple6 = (1, 3, 4)
print(len(tuple6))  #3


#查找某一個元素的個數
print(tuple6.count(3)) #1 個數1個


#查找該元素第一次出現的位置索引
print(tuple6.index(4)) #2 ,索引爲2
print(tuple6.index(4,0,3)) #2 ,索引爲2, 索引區間[0, 3),不包含3
print(tuple6.index(4,1)) #2 ,索引爲2, 索引區間[1, 3),不包含3
#print(tuple6.index(4, 0, 2))  #報異常,搜不到這個值在該區間內  ValueError: tuple.index(x): x not in tuple

#元組的比較
print(max(tuple6))  #4
tuple66 = ('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
print(max(tuple66))  #(1, 'b')  暫時不知道爲什麼
tuple7 = ('a','b','c')
tuple8 = ('e', 'f', 'g')
print(min(tuple7))  #a
print(cmp(tuple7, tuple8))  #-1, 即tuple7<tuple8 (注:0相等,1大於)

#刪除元素,只能通過拼接的方法'刪除'
tuple6 = (1, 2, 3, 4)
#del(tuple6[1])  #肯定報錯,不能修改內部元素,TypeError: 'tuple' object doesn't support item deletion
tuple6 = tuple6[:1] + tuple6[2:]
print(tuple6)  #(1, 3, 4)

#清空
del(tuple6)

tuple7 = [1, 2, 3.4, 4, 5, 6]
print(max(tuple7))  #6
print(min(tuple7))  #1

print(tuple7[2])  #3.4
print(tuple7[-2])  #5 加個負號就相當於從後往前查找 tuple7[-n] == tuple7[len(li) - n]
print(tuple7[-0])  #1  相當於list12[0],


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章