Python tuple(元组)

时间:2022-04-26
本文章向大家介绍Python tuple(元组),主要内容包括Python tuple、Python tuple 操作符、Python tuple内置函数、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

tuple即元组,与list类似,差别在于tuple中的元素一旦初始化就不可更改,即tuple是操作受限制的list(不能更改)。

list参见:https://cloud.tencent.com/developer/article/1037247

Python tuple

tuple格式:以括号作为识别符, 元素间以”,”分隔,末尾加不加”;”语法上都没错。

tup = (元素1, 元素2, 元素3,…); //;可省略

tup = (1, 2, 3, 4)
tup = (5, 6, 'a', 'b') #tuple中的元素也可以不同
tup1 = (tup, 8, "ad") #也可以是另一个tuple
tup = "e", "f", "g" #这种省略括号的写法也是对的

创建空元组tup = ();

需要注意的是创建单元素元组的时候不可以这么写tup=(1);,因为括号本身是运算符,该写法解释器无法正确识别。

正确写法: tup = (1,)

>>> tup = (1,)
>>> tup
(1,)
>>>

python tuple基本操作

tuple和list一样,每一个元素都分配了索引,与list不同tuple中的元素不能修改。你可能会疑惑,不能修改那还有什么用呢,事实上,因为不能修改,所以其值是可以确定的,所以比list要安全,因此在tuple和list都能用的情况下建议尽量多使用tuple。

>>> tup1 = ('a', 'b', 1, 2)
>>> tup2 = (1, 2, 3, 4, 5, 6)
>>> tup1[1]
'b'
>>> print ("tup1[0]: ", tup1[0])
tup1[0]: 'a'
>>> print ("tup2[1:5]: ", tup2[1:5]) #打印索引从1到4的元素,不包括5
2, 3, 4, 5

一样可以反向读取和截取

>>> tup2[-1]
6
>>> tup[1:]
(2 3 4 5 6)

但修改tuple元素操作是非法的

>>>tup1[0] = 90
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

tuple中的元素不能被删除,但可以使用del删除整个元组

>>> del tup
>>> tup
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tup' is not defined
>>>

Python tuple 操作符

Python表达式

结果

描述

len((1, 2, 3,4))

4

求tuple长度

(1, 2, 3) + ('a', 'b', 'c')

(1, 2, 3, 'a', 'b', 'c')

“+”实际上是连接

('a') * 3

('a','a','a')

“*” 实际上是复制

3 in (1, 2, 3, 4)

True

检查成员是否存在

for i in (1, 2, 3, 4) print(x)

1 2 3 4

迭代

Python tuple内置函数

方法

说明

len(tuple)

计算元组元素个数。

max(tuple)

返回元组中元素最大值。

min(tuple)

返回元组中元素最小值。

tuple(list)

将列表转换为元组。

注意: 因为tuple元素不能修改,所以也就没有类似于list的remove和append等方法。

特别注意:

当tuple中的元素为list时,虽然tuple的元素不能修改,但list的元素是可以修改的,这说明tuple的元素不变实际上指的是tuple元素的指针(或者地址)永远不变,而指针指向的内容是可以修改的。

>>> t = ('a', 'b', [1, 2])
>>> t[2][0] = 'c'
>>> t[2][1] = 'd'
>>> t
('a', 'b', ['c', 'd'])

详细的解释可以看廖雪峰的Python教程,在最底部。 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014316724772904521142196b74a3f8abf93d8e97c6ee6000