前面簡(jiǎn)單介紹了Python列表基本操作,這里再來簡(jiǎn)單講述一下Python元組相關(guān)操作
>>> 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 = () #創(chuàng)建空元組>>> tuple() #創(chuàng)建空元組()>>> (1,) #創(chuàng)建只有一個(gè)元素的元組(創(chuàng)建只有一個(gè)元素的元組,元素后面要有逗號(hào),)(1,)>>> 1,(1,)>>> 2,3 #直接用逗號(hào)隔開兩個(gè)值就可以創(chuàng)建一個(gè)元組(2, 3)>>> x,y = 2,3 #右邊為一個(gè)元組>>> x2>>> y3>>> x,y = y,x #使用元組復(fù)制,實(shí)現(xiàn)x與y交換值>>> x3>>> y2>>> t2 = (1,2,3)>>> t2[1] #獲取序號(hào)為1的元組2>>> t2[1] = 4 #元組不能改變值,這里會(huì)報(bào)錯(cuò)!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()方法統(tǒng)計(jì)元組中元素3的個(gè)數(shù)3>>> t3.index(4) # index()方法獲取元素4的位置序號(hào)4
再次提醒注意:元組不能改變其值!!
簡(jiǎn)單入門教程~
基本一看就懂~O(∩_∩)O~
未完待續(xù)~~歡迎討論!!
新聞熱點(diǎn)
疑難解答
圖片精選