python基础知识-元组

简述

python中元组与列表类似,只是元组是不可修改的类型,如果内嵌列表,则内嵌部分可以修改,元组是一种数据类型,英文为tuple

创建元组

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可

tup1 = ('jom', 'jake', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
print(tup1)
print(tup2)
print(tup3)

创建空元组与一个数据的元组,在创建一个元素的元组时,记得后面加个逗号,否则不是元组类型,而是原来的类型

tup1 = ()
tup2 = (1,)
tup3 =(1)
print(tup1)
print(tup2)
print(tup3) #输出结果为1

访问元组

元组可以通过下标的形式,来实现对元素的访问

tup1 = ('a','b','c','d','e')
print(tup1[1])
print(tup1[1:5]) #左闭右开
# 输出结果:
# b
# ('b', 'c', 'd', 'e')

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合和乘法运算

tup1 = ('a','b','c','d','e')
tup2=('d','e')
tup3=tup1+tup2
tup4=tup2*2
print(tup3)
print(tup4)
# 运行结果:
# ('a', 'b', 'c', 'd', 'e', 'd', 'e')
# ('d', 'e', 'd', 'e')

删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组

tup1 = ('a','b','c','d','e')
# del tup1[0]
# 报错:TypeError: 'tuple' object doesn't support item deletion
del tup1

常用用法和内置函数

元组运算符

Python表达式 运行结果 描述
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
(‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) 复制
3 in (1, 2, 3) True 元素是否存在
3 not in (1,2,3) False 元素是否存在
for x in (1, 2, 3): print x 1 2 3 迭代

内置函数

函数 用法
len(tuple) 计算元组元素个数
max(tuple) 返回元组中元素最大值
min(tuple) 返回元组中元素最小值
tuple(seq) 将列表转换为元组

猜你喜欢

转载自blog.csdn.net/jiuzhongxian_/article/details/106417717