字符串、列表、元组都属于序列
sequence
元组Tuple
与字符串类似,但元组不可修改
使用圆括号()
括起来,使用逗号,
隔开元素
# DateTime:2025/5/21 16:08
tup0=() # 空元组
tup1=(1,) # 单个元素,需要元素后添加逗号;否则圆括号被视为运算符
tup2=("two",5.21)
tup3=True,[3],{"three":3} # 不需要括号也可以
print(type(tup0),type(tup1),type(tup2),type(tup3))
# <class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'>
1、操作
- 索引&截取,同字符串和列表
tuple[start=0:end=len(tuple):step=1]
-
+
、+=
、*number
拼接组成新元组
# 修改元组元素报错
# tup1[0]=2 # TypeError: 'tuple' object does not support item assignment
tup4=tup1+tup2
print(tup4) # (1, 'two', 5.21)
- 单个元组中元素不允许删除,但是可以
del
整个元组
del tup4
# tup4 # NameError: name 'tup4' is not defined.
所谓元组不可变指的是元组所指向的内存中的内容不可变
# 单一元素可变对象,则内容可修改,如下: print(f"tup3={tup3},id(tup3)={id(tup3)})") tup3[1].append(4) print(f"tup3={tup3},id(tup3)={id(tup3)})") # tup3=(True, [3], {'three': 3}),id(tup3)=1898913185664) # tup3=(True, [3, 4], {'three': 3}),id(tup3)=1898913185664)
- 成员运算符
in
,not in
:判断元素是否存在 - 迭代
for i in (1,2,3):
2、Python内置函数
len(tuple)
、max(tuple)
、min(tuple)
、tuple(iterable)
数据类型转换
- 隐式类型转换:运算时自动完成
- 显示类型转换:
int(x)
、float(x)
、complex(x)
、hex(x)
、oct(x)
str(x)
、repr(x)
转为表达式字符串、tuple(x)
、list(x)
、set(x)
、frozenset(s)
转为不可变集合、dict(d)
d必须是(key,value)元组序列
eval(str)
去掉字符串前后引号
chr(x)
整数转为字符、ord(x)
字符转为整数