python之元组

 时间:2024-10-09 00:47:39

python之元组,与列表十分相似,元组和字符串一样都是不可变的,但是元组中的元素是不能修改的。另外元组使用小括号定义,而列表使用方括号。

方法/步骤

1、定义一个元组:例如:In[77]:tupe=(12,33,23.32,"zhang","qing")In[78]:tupeOut[78]:(12,33,23.32,'zhang','qing')In[79]:tupe1=(12,(12,34),"zhang")In[80]:tupe1Out[80]:(12,(12,34),'zhang')In[81]:tupe2=("zhang",[12,34,"zhang"],23)In[82]:tupe2Out[82]:('zhang',[12,34,'zhang'],23)In[83]:tupe3=('zhang',{"name":"zhang"},12)In[84]:tupe3Out[84]:('zhang',{'name':'zhang'},12)

python之元组

2、访问元组(一):In[85]:tupeOut[85]:(12,33,23.32,'zhang','qing')In[86]:tupe[0]Out[86]:12In[87]:tupe[1]Out[87]:33In[88]:tupe[2]Out[88]:23.32In[89]:tupe[3]Out[89]:'zhang'In[90]:tupe[1,3]---------------------------------------------------------------------------TypeErrorTraceback(mostrecentcalllast)<ipython-input-90-3f0c13dc8437>in<module>()---->1tupe[1,3]TypeError:tupleindicesmustbeintegersorslices,nottupleIn[91]:tupe[1:3]Out[91]:(33,23.32)

python之元组

3、访问元组(二):In[92]:tupe1Out[92]:(12,(12,34),'zhang')In[93]:tupe1[0]Out[93]:12In[94]:tupe1[1]Out[94]:(12,34)In[95]:tupe1[2]Out[95]:'zhang'In[96]:tupe1[1][1]Out[96]:34In[97]:tupe1[1][0]Out[97]:12

python之元组

4、修改元组:注意:不能对元组进行彭榧逡钚修改In[98]:tupeOut[98]:(12,33,23.32,'zha荏鱿胫协ng','qing')In[99]:tupe[1]Out[99]:33In[100]:tupe[1]=123---------------------------------------------------------------------------TypeErrorTraceback(mostrecentcalllast)<ipython-input-100-d8823ba5f314>in<module>()---->1tupe[1]=123TypeError:'tuple'objectdoesnotsupportitemassignmentIn[101]:tupe[1]="zhang"---------------------------------------------------------------------------TypeErrorTraceback(mostrecentcalllast)<ipython-input-101-7e6f9e95e567>in<module>()---->1tupe[1]="zhang"TypeError:'tuple'objectdoesnotsupportitemassignment

python之元组

5、元组内置函数之count:count与亨蚂擤缚字符串和列表中的用法相同例如:In[102]:tupeOut[102柯计瓤绘]:(12,33,23.32,'zhang','qing')In[103]:tupe.index(12)Out[103]:0In[104]:tupe.index(33)Out[104]:1In[105]:tupe.index(3)---------------------------------------------------------------------------ValueErrorTraceback(mostrecentcalllast)<ipython-input-105-0a22a2aab0ff>in<module>()---->1tupe.index(3)ValueError:tuple.index(x):xnotintupleIn[106]:tupe.index('zhang',0,4)Out[106]:3In[107]:tupe.index('zhang',0,3)---------------------------------------------------------------------------ValueErrorTraceback(mostrecentcalllast)<ipython-input-107-19c37b0692f1>in<module>()---->1tupe.index('zhang',0,3)ValueError:tuple.index(x):xnotintuple

python之元组

6、元组的内置函数之indexindex与字符串和列表中的用法相同例如:In[110]:tupeOut[110]:(12,33,23.32,'zhang','qing')In[111]:tupe.count("zhang")Out[111]:1In[112]:tupe.count("qing")Out[112]:1In[113]:tupe.count(12)Out[113]:1

python之元组

曳怎么读 微信怎么清理缓存 战三国蜀国攻略 怎么看电视型号 QQ怎么查看绑定的密保手机
热门搜索
阴虱虫子图片 纤维瘤图片 火鸡图片 绿色图片 浪琴手表价格及图片