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

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'

猜你喜欢

转载自blog.csdn.net/shfscut/article/details/80319573