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')
相关推荐
星云穿梭12 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵12 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠18 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试