python字典的key可以是列表类型吗 | 您所在的位置:网站首页 › python中不可变类型不包括 › python字典的key可以是列表类型吗 |
python中字典的key不能是可变类型。字典可存储任意类型对象,其中值可以取任何数据类型,但键必须是不可变的,如字符串、数字或元组。语法格式:【d = {key1 : value1, key2 : value2}】。 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示: d = {key1 : value1, key2 : value2 } 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 代码实现: dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} 内容扩展: Python中字典的key都可以是什么? 答:一个对象能不能作为字典的key,就取决于其有没有__hash__方法。所以所有python自带类型中,除了list、dict、set和内部至少带有上述三种类型之一的tuple之外,其余的对象都能当key。 比如数值/字符串/完全不可变的元祖/函数(内建或自定义)/类(内建或自定义)/方法/包等等你能拿出手的,不过有的实际意义不高。还有数值型要注意,因为两个不同的相等数字可以有相同的哈希值,比如1和1.0。 解释: 代码版本:3.6.3;文档版本:3.6.6 Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append()and extend(). 字典的键可以是任意不可变类型,需要注意的是tuple元组作为键时,其中不能以任何方式包含可变对象。 到此这篇关于python字典key不能是可以是啥类型的文章就介绍到这了,更多相关python字典key不能是什么类型内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们! 时间: 2020-08-04 |
CopyRight 2018-2019 实验室设备网 版权所有 |