Python--04--数据容器(元组)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


元组

1.概述

元组:用来存放一组有序的数据,但其中的内容一旦创建就不可修改(不能增、删、改,只能查)。

2.定义元组



3.读取数据

4.元组不可修改

5.元组的常用方法

6.元组的常用内置函数

python 复制代码
# 常用内置函数
# max 函数,返回元组中的最大值
t1 = (23, 11, 32, 30, 17)
result = max(t1)
print(result)  # 32

# min 函数,返回元组中的最小值
t1 = (23, 11, 32, 30, 17)
result = min(t1)
print(result)  # 11

# len 函数,返回元组中元素的个数(元组长度)
t1 = (23, 11, 32, 30, 17)
result = len(t1)
print(result)  # 5

# sorted 函数,对元组进行排序(不修改原元组,返回一个新的列表)
t1 = (23, 11, 32, 30, 17)
result = sorted(t1, reverse=True)
print(tuple(result)) # (32, 30, 23, 17, 11)

# sum 函数,统计元组中所有元素的和(元素必须是纯数字)
t1 = (23, 11, 32, 30, 17)
result = sum(t1)
print(result) # 113

7.元组的循环遍历

8.解包列表或元组传参

python 复制代码
# 定义函数时,使用*args(变量不一定非要用args,比如写:*data也行),将收到的多个参数,打包成一个元组
def test(*args):
    print(f'我是test函数,我收到的参数是:{args},参数类型是:{type(args)}')

list1 = [100, 200, 300, 400]
tuple1 = ('你好', '北京', '尚硅谷')

# 函数调用时,正常传递:列表 或 元组
test(list1)
test(tuple1)

print('=============================')
# 函数调用时,使用*对:列表 或 元组进行解包后,再传递参数
test(*list1)  # 此种写法相当于:test(100, 200, 300, 400)
test(*tuple1)  # 此种写法相当于:test('你好', '北京', '尚硅谷')

9.元组特点总结



相关推荐
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋2 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama