前面簡單介紹了Python列表基本操作,這里再來簡單講述一下Python元組相關操作
>>> dir(tuple) #查看元組的屬性和方法['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']>>> t1 = () #創建空元組>>> tuple() #創建空元組()>>> (1,) #創建只有一個元素的元組(創建只有一個元素的元組,元素后面要有逗號,)(1,)>>> 1,(1,)>>> 2,3 #直接用逗號隔開兩個值就可以創建一個元組(2, 3)>>> x,y = 2,3 #右邊為一個元組>>> x2>>> y3>>> x,y = y,x #使用元組復制,實現x與y交換值>>> x3>>> y2>>> t2 = (1,2,3)>>> t2[1] #獲取序號為1的元組2>>> t2[1] = 4 #元組不能改變值,這里會報錯!Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> t2[1] = 4TypeError: 'tuple' object does not support item assignment>>> t3 = (2,3,3,3,4,5)>>> t3.count(3) # count()方法統計元組中元素3的個數3>>> t3.index(4) # index()方法獲取元素4的位置序號4
再次提醒注意:元組不能改變其值??!
簡單入門教程~
基本一看就懂~O(∩_∩)O~
未完待續~~歡迎討論??!
新聞熱點
疑難解答