• 6数据类型3


    数据类型3

    可变和不可变类型

    hash函数

    1:可变和不可变的数据类型

    到现在,我们已经理解了数字,字符串,列表,元组数据类型

    在python中,我们对数据类型还有另外一种分类方式,我们给数据类型分为可变数据类型和不可变数据类型。在了解原理之前,我们先来看看分类情况:

    可变类型:列表

    不可变类型:数字 , 字符串 , 元组

    举个例子:

    列表

    >>> l = [1,2,3,4]

    >>> id(l)

    21314136

    >>> l[1] = 1.5 # 修改里面的元素

    >>> id(l) # 发现整体的内存地址没有变化

    21314136

    >>> id(l[1]) # 索引为1的内存地址

    58572944

    >>> l[1] = 6 # 修改索引为1 的值

    >>> id(l[1]) # 索引为1的内存地址 发现发生了变化

    262396160

    数字:

    >>> a = 1

    >>> id(a)

    4297537952

    >>> a+=1

    >>> id(a)

    4297537984

    字符串:

    #1

    >>> s = 'hello'

    >>> s[1] = 'a'

    Traceback (most recent call last):

    File "<pyshell#5>", line 1, in <module>

    s[1] = 'a'

    TypeError: 'str' object does not support item assignment

    #2

    >>> s = 'hello'

    >>> id(s)

    4392917064

    >>> s += ' world'

    >>> s

    'hello world'

    >>> id(s)

    4393419504

    字符串也可以像列表一样使用索引操作,但是通过上例可以看出,我们不能像修改列表一样修改一个字符串的值,当我们对字符串进行拼接的时候,原理和整数一样,id值已经发生了变化,相当于变成了另外一个字符串。

    元组—不可修改

    >>> t = (1,2,3,4)

    >>> t[1] = 1.5

    Traceback (most recent call last):

    File "<pyshell#10>", line 1, in <module>

    t[1] = 1.5

    TypeError: 'tuple' object does not support item assignment

    2:hash函数:

    可变的数据类型是不可以被hash的,如果一个值可以hash那么说明这是一个不可变得数据类型。

    Hashing 将一段数据(无论长还是短)转成相对较短的一段数据,例如一个字符串或者一个整数。

    这是通过使用单向哈希函数来完成的。"单向" 意味着逆转它是困难的,或者实际上是不可能的。

    加密可以保证信息的安全性,避免被拦截到被破解。Python 的加密支持包括使用 hashlib 的标准算法(例如 MD5 和 SHA),根据信息的内容生成签名,HMAC 用来验证信息在传送过程中没有被篡改。

    >>> a = 123

    >>> b = 123

    >>> hash(a)

    123

    >>> hash(b)

    123

    >>> c = [1,2]

    >>> hash(c)

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    TypeError: unhashable type: 'list'

    >>> hash(c[1])

    2

    >>> d = '123'

    >>> hash(d)

    -1699721517

    >>> e = (1,23,4)

    >>> hash(e)

    740729019

    >>> help(hash)

    Help on built-in function hash in module builtins:

    hash(obj, /)

    Return the hash value for the given object.

    Two objects that compare equal must also have the same hash value, but the

    reverse is not necessarily true.

    菜鸟的自白
  • 相关阅读:
    python os
    [BZOJ2887] 旅行
    UVA1104 Chips Challenge
    CF364E Empty Rectangles
    CF1408H Rainbow Triples
    CF1214G Feeling Good
    CF506E Mr. Kitayuta's Gift
    采用Canal监听mysql数据库变化
    Java8 ParallelStream
    Java8 方法引用
  • 原文地址:https://www.cnblogs.com/lzjloveit/p/10584947.html
Copyright © 2020-2023  润新知