元组类型

元组(tuple)是表示有序不可变元素的集合,元素可以是任意类型,元组就是不可变的列表。

元组的定义

元组通过一对小括号进行定义,元素之间使用逗号隔开。

>>> a = ()          # 空元组
>>> print(type(a))
<class 'tuple'>
>>> b = ('a', 'b', 'c')    # 字符串
>>> print(type(b))
<class 'tuple'>
>>> c = (1, 2, 3)      # 数字
>>> print(type(c))
<class 'tuple'>
>>> d = (1, 2, ['a', 'b'])  # 列表
>>> print(type(d))
<class 'tuple'>
>>> e = (1, 2, (1, 2))    # 元组
>>> print(type(e))
<class 'tuple'>

注意单元素元组的定义,一定要多加个逗号

>>> f = ('hello')
print(f, type(f))
'hello' <class 'str'>
>>> g = ('hello', )
print(g, type(g))
('hello', ) <class 'tuple'>

元组的索引和切片

序列的索引和切片完全一致,参考字符串。

>>> t = (1,2,3,4,5,6,7,8,9)
>>> t[0]
1
>>> t[:3]
(1,2,3)

元组的常用操作

元组一旦创建,元素就不可改变,没有增删改操作。

元组的常用方法

元组只有两个公有方法count, index用法与列表相同。

len函数

python的内建函数len可以获取对象中包含元素的个数

>>> s = 'hello'
>>> len(s)
5
>>> ls = [1,2,3]
>>> len(ls)
3
>>> t = (1,2,3)
>>> len(t)
3
posted @ 2022-08-19 17:32  python心蓝  阅读(260)  评论(0编辑  收藏  举报