Python 学习笔记(八)
程序员文章站
2022-07-09 23:22:35
...
元组
元组是一个位置有序的对象的集合,属于序列类型。元组属性和列表相似,但元组是不可变类型。
In [1]: t = ('alex', 'seven', 'eric') # 1
In [2]: t
Out[2]: ('alex', 'seven', 'eric')
In [3]: t = tuple(['alex', 'seven', 'eric']) # 2
In [4]: t
Out[4]: ('alex', 'seven', 'eric')
In [5]: t[1] = "hello"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-865820d988eb> in <module>()
----> 1 t[1] = "hello"
TypeError: 'tuple' object does not support item assignment
元组基本操作
-
count(self, object)
统计对象在元组中出现的次数
In [1]: a = ('alex', 'eric', 'seven')
In [2]: a.count('alex')
Out[2]: 1
-
index(self, object)
对象在元组中位置
In [1]: a = ('alex', 'seven', 'eric')
In [2]: a.index('alex')
Out[2]: 0