Python - tuple

声明tuple

python 复制代码
>>> a = (3)
>>> type(a)
<class 'int'>
>>> b = 3
>>> type(b)
<class 'int'>
>>> c = (3,)
>>> type(c)
<class 'tuple'>

元组中只有一个元素时,应该在元素后面追加一个半角的英文逗号,避免Python误解。

元组特点

  • 元素比列表操作速度快。如果定义了一个值的常量集,并且需要遍历,可适用元素替代列表。
  • 如果对不需要修改的数据进行"写保护",可以使代码更安全,此时使用元组而不是列表。如果必须改变这些值,则需要将元组转为列表后再转换。
  • 元素可以在字典中被用作key,但是列表不行。字典的key不可变,元组本身也是不可变的。
  • 元组可以用在字符串格式化中。

字典的键

复制代码
>>> d1 = {(1,2):1}
>>> d2 = {[1,2]:1}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

字典的key,可以为元组,但不能是list。

unhashable 指 可变的。

元素格式化字符串

python 复制代码
>>> name_age = ("Jack", 18)
>>> print("My name is {}, and I'm {} years old.".format(*name_age))  # 使用*解包元组
My name is Jack, and I'm 18 years old.

>>> name, age = ("Jack", 18)
>>> print("My name is {}, and I'm {} years old.".format(name,age))  # 使用位置参数 
My name is Jack, and I'm 18 years old.

# % 主要用于单个变量或值的格式化,通过元组提供多个值。需要注意参数的顺序和数量必须与格式字符串中的占位符匹配。
>>> print("My name is %s, and I'm %d years old." %(name, age))
My name is Jack, and I'm 18 years old.
相关推荐
devilnumber1 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
大貔貅喝啤酒2 小时前
Python Requests库教程
自动化测试·python·requests库
copyer_xyf2 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf2 小时前
Prompt 组织管理
后端·python·agent
asdfg12589633 小时前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
Cutecat_3 小时前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
shimly1234563 小时前
python3 uvicorn 是啥?
python
qq_422152573 小时前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen3 小时前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
CTA量化套保4 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链