Python(七) 元组

元组(tuple)与列表类似,但元组是不可变的,可简单将其看作是不可变的列表,元组常用于保存不可修改的内容,元组使用小括号 ( ),列表使用方括号 [ ]。

使用

访问

python 复制代码
t = (1024,0.5,'Python',"Java")
print(t)
print(t[1])
print(t[1:3])

#输出
(1024, 0.5, 'Python', 'Java')
0.5
(0.5, 'Python')

更新

元素值是不允许修改的,可以用重新赋值来操作,也可以对元组进行连接组合

python 复制代码
t = (1024,0.5,'Python',"Java")
t = (1024, 0.5, 'Python', 'Hello')
print(t)

t1 = (123,456,789)
print(t+t1)

#输出
(1024, 0.5, 'Python', 'Hello')
(1024, 0.5, 'Python', 'Hello', 123, 456, 789)

删除

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

python 复制代码
t2 = (1,2,'aa')
del t2
print('删除后:')
print(t2)

#输出,元组被删除后,输出会报错
删除后:
Traceback (most recent call last):
     print(t2)
NameError: name 't2' is not defined. 

常用函数

|---------|-------------|
| len() | 返回元组元素个数 |
| min() | 返回元组中元素最小值 |
| max() | 返回元组中元素最大值 |
| tuple() | 将可迭代系列转换为元组 |

python 复制代码
t = ('d', 'b', 'a', 'f', 'd')
print(len(t))
print(min(t))
print(max(t))

l = ['d', 'b', 'a', 'f', 'd']
tt = tuple(l)
print('tt -->', tt)

#输出
5
a
f
tt --> ('d', 'b', 'a', 'f', 'd')
相关推荐
用户8356290780512 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon3 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly3 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程4 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly5 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风12 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风12 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python