Python-元组详解

注意:列表是方括号【】,元组是圆括号(),这里要分清。

创建元组

1、a = ()

2、b = tuple()

python 复制代码
a = ()
b = tuple()

2、可以指定初始值

a = (1,2,3,4)

python 复制代码
a = (1,2,3,4)

3、元素可以是任意类型

a = (1,2,3,4,'hello')

python 复制代码
a = (1,2,3,4,'hello')

4、可以通过下标访问元素

下标也是从0开始

下标可以为负数,表示的意思依旧是从len - 1,即倒数元素开始

5、可以切片

a[1:3]左闭右开

python 复制代码
a = (1,2,3,4,5,6)
b = a[1:3]#左闭右开,b的结果为(2,3,4)

6、可以使用for循环进行遍历

a = (1,2,3)

for elem in a:

print(a)

python 复制代码
a = (1,2,3)
for elem in a:
    print(a)

7、index查找下标

print(2 in a)

a.index(2)

python 复制代码
print(2 in a)
a.index(2)

8、使用 + 拼接元素

a

b

a + b

python 复制代码
a = (1,2,3)
b = (4,5,6)
c = a + b

元组是不能修改
支持只读,不支持写入

相关推荐
曲幽8 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805113 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon14 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly14 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程15 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python