Python元组详解

元组是python内置数据结构之一,是一个不可变序列。

元组的特点:有序,可多种不同数据类型的元素混合存储,允许有重复数据,不可变序列(所以没有元组生成式)。

在程序中要尽量使用不可变序列

因为一旦创建了不可变对象,对象内部的所有数据就都不能被修改,这样可以避免由于修改数据而导致的错误。并且,对于不可变对象,在多任务环境下,同时操作对象的时候就不需要加锁。

创建元组

1)使用(),元素用英文版的逗号隔开

t = ('hello','python',80,'world')
print(type(t))  # <class 'tuple'>
print(t)        # ('hello', 'python', 80, 'world')

# 多个元素,()可以省略
t = 'hello','python',80,'world'
print(type(t))  # <class 'tuple'>
print(t)        # ('hello', 'python', 80, 'world')

2)使用内置函数 tuple()

t1 = tuple(('hello','python',80,'world'))
print(type(t1))  # <class 'tuple'>
print(t1)        # ('hello', 'python', 80, 'world')

3)创建只包含一个元素的元组

元组只包含一个元素时,那个元素后面必须加上逗号,否则会被认为是那个元素本身的数据类型。

t2 = ('python')
print(type(t2),t2)  # <class 'str'> python

# ,不能省略,否则就会被认为是它(那个元素)本身的数据类型
t3 = ('python',)
print(type(t3),t3)  # <class 'tuple'> ('python',)
# ()可以省略,但,不能省
t4 = 'python',
print(type(t4),t4)  # <class 'tuple'> ('python',)

4)创建空元组

t1 = ()
print(type(t1),t1)  # <class 'tuple'> ()
t2 = tuple()
print(type(t2),t2)  # <class 'tuple'> ()

元组的查询操作

1)[] 适合知道元素个数,否则越界会抛出异常

元组是有序的,所以可以通过索引号来访问元组中的元素。

t = ('hello','python',80,'world')
print(t[1])     # python
# print(t[6])     # IndexError: tuple index out of range

2)遍历元组 不知道元素个数

t = ('hello','python',80,'world')

for i in t:
    print(i)

3)使用in/not in判断指定元素是否存在

t = ('hello','python',80,'world')
print(80 in t)  # True
print('hello' in t) # True
print(999 in t)     # False

更改元组值

元组是不可变序列,一旦创建后,就无法更改元组值。

元组中存储的是对象的引用。如果元组中的对象本身是不可变对象,则不能再引用其他对象。如果元组中的对象是可变对象,则可变对象的引用不允许改变,数据是可以改变的(不能更改元素的地址,但是可以对那个可变对象进行操作),比喻说

t = (10,[33,66],'world')
print(id(t),t)          # 1645663339968 (10, [33, 66], 'world')
print(id(t[0]),t[0])    # 1645654704656 10
print(id(t[1]),t[1])    # 1645663416448 [33, 66]       t[1]是一个列表,是可变对象

# t[0]是不可变对象,他不能在引用其他对象
# t[0] = 111  # TypeError: 'tuple' object does not support item assignment

# t[1]是可变对象,但在元组中,它的引用是不能改变的,只能改变他的数据
# t[1] = 999  # TypeError: 'tuple' object does not support item assignment

t[1].append(999)    # 列表中添加元素不会产生新的对象
print(id(t[1]),t[1])    # 1645663416448 [33, 66, 999]
print(id(t),t)          # 1645663339968 (10, [33, 66, 999], 'world')

还可以将元组转换为列表,修改列表,然后再将列表转换为元组。

t = ('hello','python',80,'world')
print(t,type(t))
lst = list(t)       # 将元组转换为列表
print(lst,type(lst))
lst[1] = 999
t1 = tuple(lst)
print(t1,type(t1))

删除元组

无法删除元组中的元素。只能使用 del 关键字完全删除元组对象。

t = ('hello','python',80,'world')
del t
print(t)    # NameError: name 't' is not defined. Did you mean: 't1'?

获取元组的长度

使用len()方法

t = ('hello','python',80,'world')
print(len(t))   # 4

合并元组

使用+

t1 = (10,30,'hello')
t2 = (99,'python')
t3 = t1 + t2
print(t3)   # (10, 30, 'hello', 99, 'python')
© 版权声明
THE END
喜欢就支持一下吧
点赞16 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容