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.
相关推荐
ZhengEnCi37 分钟前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
狗头大军之江苏分军2 小时前
《潮水漫过十七岁》倒计时
前端·javascript·后端
Wellijohn2 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
小码哥0683 小时前
租房平台源码部署验收:房源样例、区域字典与看房预约逐项验证
前端·javascript·vue.js·租房小程序·租房系统·租房软件
bufengwangluo3 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶3 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
htzyl2063 小时前
JS原型链与继承:class 底下到底是什么
前端·javascript·ecmascript 6
一条Go3 小时前
15 套品牌色 + 双模式:把颜色关进三层 token
前端·github