4

Python 简明教程 --- 11,Python 元组

 2 years ago
source link: https://codeshellme.github.io/2020/05/python-learn11/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

微信公众号:码农充电站pro

个人主页:https://codeshellme.github.io

软件工程的目标是控制复杂度,而不是增加复杂性。

—— Dr. Pamela Zave

目录

我们在上一节介绍了Python 列表list 数据结构,本节来介绍一下元组tuple

1,Python 元组

元组与列表有些相似,它们之间最显著的不同是,元组一旦定义了以后,就不能再修改(增加/删除其中的元素),而列表可以被任意的改。

Python 元组有如下特点:

  • 元组中的元素可以是任意类型的数据
  • 可使用下标和切片访问元组内容
  • 元组一点定义,不能再被修改

2,定义元组

我们已经知道了定义列表使用中括号[],而定义元组使用小括号() 表示:

>>> t = () # 一个空的元组
>>> t
>>> t = ('a', 1, 3.5, True) # 元组中可以存放任意类型
>>> t
('a', 1, 3.5, True)

只有一个元素的元组

当定义的元组中只有一个元素时,需要在元素后边加个逗号:

>>> t = (1,)
>>> t

如果没带逗号,则这个小括号()将不会被认为是元组符号:

>>> t = (1) # 相当于没有带小括号
>>> t
>>> t = ('abc')
>>> t
'abc'

3,元组的大小

可以使用len() 来查看一个元组的大小:

>>> t = ('a', 'b', 'c')
>>> len(t) # 长度为 3
>>> t = (1, 3)
>>> len(t) # 长度为 2

4,访问元组

可以像访问列表一样,使用下标切片,和 for 循环来访问元组。

使用下标访问元组

>>> t = ('a', 'b', 'c')
>>> t[0] # 访问第一个元素
>>> t[3] # 下标越界
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> t[-1] # 访问倒数第一个元素
>>> t[-3] # 访问倒数第三个元素
>>> t[-4] # 下标越界
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

使用切片访问元组

>>> t = ('a', 'b', 'c')
>>> t[1:3]
('b', 'c')
>>> t[2:]
('c',)
>>> t[:3]
('a', 'b', 'c')
>>> t[:]
('a', 'b', 'c')

遍历元组

>>> t = ('a', 'b', 'c')
>>> for i in t:
... print(i)

5,元组不可修改

元组是不可变类型,不能对一个已定义的元组进行以下操作,否则会抛出异常:

>>> t = ('a', 'b', 'c')
>>> # 没有对于元组的添加操作,所以也不用演示
>>>
>>> t[0] = 1 # 修改元素,抛出异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
>>> del t[1] # 删除元素,抛出异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

6,元组运算

像列表一样,元组也可以进行加运算乘运算in 运算

>>> ('a', 'b') + (1, 2) # 加运算,得到一个新的元素
('a', 'b', 1, 2)
>>>
>>> ('a', 'b') * 2 # 乘运算,相当于 n 个元素相加
('a', 'b', 'a', 'b')
>>>
>>> ('a', 'b') * -1 # n 小于等于 0 时,得到一个空元组
>>> 'a' in ('a', 'b') # in 运算,判断一个元素是否包含在元组中
>>> 'a' not in ('a', 'b')
False

7,元组函数

通过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']

可以看到处了魔法方法,元组类型仅支持两个方法:

  • count 方法
  • index 方法

且没有任意一个方法用于修改元组。

1.count 方法

作用:计算元组T 中值为value 的个数

原型:T.count(value) -> integer

参数:要计算的元素的值

返回值:个数

>>> t = ['a', 'b', 'c', 'a']
>>> t.count('a')
>>> t.count('b')
>>> t.count('d')

2.index 方法

作用:从元组T[start:stip] 中查找第一个值为value 的元素

原型:T.index(value, [start, [stop]]) -> integer

参数 value:查找值为value 的元素

参数 start:元组T 的起始下标

参数 stop:元组T 的终止下标

返回值:若能找到,则返回该元素的下标,否则,抛出ValueError 异常

>>> t = ['a', 'b', 'c']
>>> t.index('b') # 找到了,返回下标
>>> l.index('d') # 没找到,抛出 ValueError 异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'd' is not in list

推荐阅读:

Python 简明教程 — 6,Python 控制流

Python 简明教程 — 7,Python 字符串

Python 简明教程 — 8,Python 字符串函数

Python 简明教程 — 9,Python 编码

Python 简明教程 —10,Python 列表


欢迎关注作者公众号,获取更多技术干货。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK