重新开始学习 Python 第七天

Python 元组

元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。

创建元祖与创建列表类似,用圆括号扩起来就可以了,例如

>>> tup=('TOM','Jerry')

>>>

>>> tup

('TOM', 'Jerry')

>>> type(tup)

<class 'tuple'>

>>>

元组和列表有一些是相同的,也有不同点,不同点不光光提现在各自的声明上,还有一个重要的不同点就是,元组声明后不能像列表一样实现修改。

>>> tup

('TOM', 'Jerry')

>>> tup[1]="ED"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

>>>

#但是可以这样修改元组,其意义就是创建一个新的元组

>>> tup = tup + ("ED",)

>>>

>>> tup

('TOM', 'Jerry', 'ED')

>>>

删除元组

del(tup)

查询元组

查询元组其实就是按照元组的索引进行遍历,或者分片。

>>> for x in tup:

... print(x)

...

TOM

Jerry

ED

>>>

元组分片与其他基本类型一致,这里只是举例子,不作详细叙述了。

>>> tup[0:]

('TOM', 'Jerry', 'ED')

>>> tup[0:-1]

('TOM', 'Jerry')

>>> tup[-1:]

('ED',)

>>>

>>> tup[-2:]

('Jerry', 'ED')

>>>

元组常用的内置函数

>>> tup

('TOM', 'Jerry', 'ED')

>>> len(tup) #tup元组长度

3

>>> max(tup) #tup元组最大值 元组中的数据类型是一致的,这样才能比较,字符串的话是按照ASCII码进行排序。若是数字的话,是按照大小排序

'TOM'

>>> min(tup) # tup元组最小值,参照max()函数。

'ED'

>>> tuple(['1',2,3,4]) #将列表转换为元组。

('1', 2, 3, 4)

>>>

>>> dir(tup)

['__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']

>>>

发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();