python攻克之路day4

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python攻克之路day4相关的知识,希望对你有一定的参考价值。

 

day4内容

字典的key都能是什么

  字典查找速度快,基于哈希索引

  字典的key只能是不可变类型

不可变:str,int,bool,tuple

可变类型:list,dict,set

 

不可变类型

dic = {
     ‘k1‘:‘v1‘,
      2:‘v1‘
     False:‘v1‘
     (11,22,33):‘v1‘,   
}
print(dic)#{‘k1‘: ‘v1‘, 2: ‘v1‘, False: ‘v1‘, (11, 22, 33): ‘v1‘}

  

可变类型

dic = {

    ‘k1‘:‘v1‘,
    2:‘v1‘,
    False:‘v1‘,
    [11,22,33]:‘v1‘,
}
print(dic)#TypeError:ynhashable type:‘list‘  不可哈希

  

           字典的方法

技术分享
data = [11,22,33,44]
dic1 = {
    k1: v1,
    k2: data
}

dic2 = {
    k1: v1,
    k2: data
}
data.append(666)
print(dic1)
print(dic2)
append
技术分享
dic1 = {
    k1: v1,
    k2: [11,22,33,44]
}
dic2 = dic1.copy()
print(dic1,dic2)
dic1[k2].append(666)
print(dic1,dic2)

dic1 = {
    k1: v1,
    k2: [11,22,33,44]
}
import copy
dic2 = copy.deepcopy(dic1)
print(dic1,dic2)
dic1[k2].append(666)
print(dic1,dic2)
copy
技术分享
dic = {k1:v1,k2:v2}
v = dic.pop(k23,默认值)
print(dic)
print(v)
pop
技术分享
dic = {k1:v1,k2:v2}
v1,v2 = dic.popitem()
print(dic)
print(v1,v2)
popitem
技术分享
# dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}
# 添加
# dic.setdefault(‘k2‘,‘999‘)
# print(dic)
# 设置:添加,修改
# dic[‘k2‘] = 999
setdefault
技术分享
dic = {k1:v1,k2:v2} # dict类的一个对象
dic.update({k4:v4,k2:v5})
print(dic)
update
技术分享
val = dict.fromkeys([k1,k2,k3],666)
print(val)
val[k1] = 999

val = dict.fromkeys([k1,k2,k3],[])
val[k1].append(678)
val[k2].append(999)
print(val)

val = dict.fromkeys([k1,k2,k3],[])
val[k1].append(666)
val[k1] = [1,2,3]
print(val)

v = [11,22,33]
v.append(55)  # 修改内部
v = [1,2,3]

v1 = "strasdf"
v = "sfsfs"
fromkeys

 

以上是关于python攻克之路day4的主要内容,如果未能解决你的问题,请参考以下文章

Python之路,Day4 - Python基础4

python学习day4之路文件的序列化和反序列化

Python之路,Day4

python之路-Day4

Python之路day4

python学习之路-day4.1