(python拓展) —— 可变和不可变类型 等

128 阅读2分钟

可变和不可变类型

  • 不可变类型,内存中的数据不允许被修改
  1. 数字类型 int,boolean,float,complex,long(2.x)
  2. 字符串 string
  3. 元组 tuple
  • 可变类型,内存中的数据可以被修改
  1. 列表 list
  2. 字典 dictionary

字典 dictionary 键值对

哪些数据可以作为键值对的 key ?

  • String 可以
String  # 可以  a["a1"] = "this is String" 
In [64]: a
Out[64]: {'a1': 'this is String'}
  • Number 可以
Number  # 可以 a[1] = "this is Number"
In [67]: a
Out[67]: {'a1': 'this is String', 1: 'this is Number'}

-Tuple 可以

Tuple 	# 可以	 a[(1,)] = "this is tuple"
In [69]: a
Out[69]: {'a1': 'this is String', 1: 'this is Number', (1,): 'this is tuple'}
  • list 不可以
list    # 不可以  a[[1,2,3]] = "this is list"
TypeError                                 Traceback (most recent call last)
Input In [72], in <cell line: 1>()
----> 1 a[[1,2,3]] = "this is list"
TypeError: unhashable type: 'list'
  • dictionary 不可以
dictionary   # 不可以  e[{"1":"a"}] = "hao"
TypeError                                 Traceback (most recent call last)
Input In [92], in <cell line: 1>()
----> 1 e[{"1":"a"}] = "hao"

TypeError: unhashable type: 'dict'

hash()

内置函数,用于获取一个对象(string或者数值)的哈希值(特征码)
接收 不可变类型作为参数(每一次数值变化,都会生成一个新的哈希码)

  • hash中的参数不变的情况下,返回的整数保持不变
  • hash中的参数发生变化,返回的整数也会发生变化 返回一个整数
  • 接收的类型:
    String
In [93]: hash("1")
Out[93]: -4860779926127071570

Number

In [95]: hash(2)
Out[95]: 2

Tuple

In [96]: hash((1,))
Out[96]: -6644214454873602895
  • 不接收的类型:
    list
In [97]: hash([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [97], in <cell line: 1>()
----> 1 hash([1,2,3])

TypeError: unhashable type: 'list'

dictionary

In [98]: hash({"a":1})
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [98], in <cell line: 1>()
----> 1 hash({"a":1})

TypeError: unhashable type: 'dict'