《python必学模块-collections》第2章 tuple功能详解

本文探讨了Python中元组(tuple)与列表(list)的主要区别,重点介绍元组的不可变性和作为字典键的应用场景。通过示例说明了元组的迭代、拆包、不可变性以及在实际编程中的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

name_tuple=('bobby1', 'bobby2')

# tuple是iterable
# 实现了魔法函数__iter__或__getitem__就是iterable的
for name in name_tuple:
    print(name)

# tuple的拆包
user_tuple=('bobby', 29, 175)
name, age, height=user_tuple
print(name, age, height)        # bobby 29 175

user_tuple=('bobby', 29, 175, 'beijing', 'edu')
name, *other = user_tuple
print(name, other)              # bobby [29, 175, 'beijing', 'edu']

# tuple不可变
name_tuple = ('bobby1', 'bobby2')
name_tuple[0] = 'shf'  # 报错
# tuple不可变不是绝对的,但是不建议在tuple中存放可变对象[29,175]
name_tuple = ('bobby1', [29, 175])
name_tuple[1].append(22)


user_info_dict={}
user_info_dict[user_tuple]='bobby'
print(user_info_dict)

# list就不可以
user_info_dict[['bobby', 29,175]]='bobby' # 报错:TypeError:unhashable type:'list'

既然已经有了list,为什么还需要使用tuple?
其中一个重要特性是tuple可以作为dict的key,为什么呢?因为tuple是immutable的,所以tuple是hashable(可哈希的)

这里写图片描述

user_info_dict={}
user_info_dict[user_tuple]='bobby'
print(user_info_dict)       # {('bobby', 29, 175): 'bobby'}

# list就不可以
user_info_dict[['bobby', 29,175]]='bobby' # 报错:TypeError:unhashable type:'list'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值