python学习_18

Posted

tags:

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

字典
字典是无序的
字典的key只能是不可变对象,不能是list dict
创建字典
创建空字典,并赋值

>> d = {}
>> d["name"] = "huhongqiang"
>> d["sex"] = "M"
>> d["height"] = 170
>> d
{‘name‘: ‘huhongqiang‘, ‘sex‘: ‘M‘, ‘height‘: 170}

直接创建

>> d2 = {"a":1,"b":2,"c":3}
>> d2
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}

>> d1={}
>> for k in sorted(dict.keys()):
... d={k:dict[k]}
... d1.update(d)
...
>> d1
{20: ‘b‘, 200: ‘a‘, 610: ‘c‘}

dict()创建字典

>> d = dict(name ="hhq",sex="m",schook="jx")
>> d
{‘name‘: ‘hhq‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘}

参数是列表,每个列表是包含两个元素的元组

>> d1 = dict([("name","hhq"),("sex","m"),("school","jx")])
>> d1
{‘name‘: ‘hhq‘, ‘sex‘: ‘m‘, ‘school‘: ‘jx‘}

>> d2 = dict(zip(["name","sex","schook"],["hhq","m","jx"]))
>> d2
{‘name‘: ‘hhq‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘}

>> list(zip(["name","sex","schook"],["hhq","m","jx"]))
[(‘name‘, ‘hhq‘), (‘sex‘, ‘m‘), (‘schook‘, ‘jx‘)]

dict.fromkeys(seq[,value])
序列 seq的元素作为字典的key,value作为字典的值,返回一个字典

Value为可选参数,不指定字典的值为None

>> lst = ["x","y","z"]
>> d_1 = dict.fromkeys(lst,10)
>> d_1
{‘x‘: 10, ‘y‘: 10, ‘z‘: 10}

>> d_2 = dict.fromkeys(lst)
>> d_2
{‘x‘: None, ‘y‘: None, ‘z‘: None}

访问字典的值

>> d["name"]
‘hhq‘
>> d["sex"]
‘m‘

修改字典的值>>> d
{‘name‘: ‘hhq‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘}

>> d["name"] = "xxxxxxxxxx"
>> d
{‘name‘: ‘xxxxxxxxxx‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘}

字典新增键值对

>> d["xx"] ="yy"
>> d
{‘name‘: ‘xxxxxxxxxx‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘, ‘xx‘: ‘yy‘}

删除元素

>> del d["name"]

清空元素

>> info.clear()
>> info
{}

删除字典

>> del d
>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘d‘ is not defined

str(dict)
输出字符串表示的字典

>> str(d2)
"{‘name‘: ‘hhq‘, ‘sex‘: ‘m‘, ‘schook‘: ‘jx‘}"

len()求字典元素个数

遍历字典的key
dict.keys()可理解返回一个列表

可直接遍历字典名,返回key值

>> for k in info:
... print(k)
...
>> for k in info.keys():
... print(k)
...

遍历字典的value

>> for v in d2.values():#列表
... print(v)
...
hhq
m
jx
>> d2.values()
dict_values([‘hhq‘, ‘m‘, ‘jx‘])

遍历字典的键值对
返回键值对元组组成的列表

>> d2.items()
dict_items([(‘name‘, ‘hhq‘), (‘sex‘, ‘m‘), (‘schook‘, ‘jx‘)])

字典的排序
利用sorted()函数

按照key排序,d.items()是一个列表,列表的元素是包含key、value的元组

>> sort_key = sorted(d.items(),key=lambda x:x[0],reverse=False)
>> sort_key
[(‘a‘, 5), (‘b‘, 1), (‘c‘, 3), (‘d‘, 4)]
>> dict(sort_key)
{‘a‘: 5, ‘b‘: 1, ‘c‘: 3, ‘d‘: 4}

按照value排序

>> sort_value = sorted(d.items(),key=lambda x:x[1],reverse=False)
>> sort_value
[(‘b‘, 1), (‘c‘, 3), (‘d‘, 4), (‘a‘, 5)]
>> dict(sort_value)
{‘b‘: 1, ‘c‘: 3, ‘d‘: 4, ‘a‘: 5}

练习:d={-1:100,-2:200,0:300,-3:200}按照key的大小顺序升序进行输出,输出key=value -3=200,-2=200,-1=100,0=300

d = {-1: 100, -2: 200, 0: 300, -3: 200}

for k in sorted(d.keys()):
print("%s=%s" %(k,d[k]),end=",")

>> for k,v in sorted(d.items(),key=lambda x:x[0]):
... print(str(k) + "=" + str(v),end="")
...

2.一个字符串排序,排序规则:小写<大写<奇数<偶数,
原理:先比较元组的第一个值,FALSE<TRUE,如果相等就比较元组的下一个值,以此类推。

s=‘9a13C85c7B24A6b‘#正确的顺序应该为:abcABC135792468
lis=sorted(s,key=lambda?x:(x.isdigit(),x.isdigit()?and?int(x)%2==0,x.isalpha()?and?x.isupper(),x.isalpha()?and?x.islower()))
s = sorted(list(s))
lst = sorted(s,key = lambda x:(x.isdigit(),x.isdigit() and int(x)%2 ==0 ,x.isalpha() and x.isupper(),x.isalpha()  and x.islower()))
print("".join(lst))

小写<大写<奇数<偶数
偶数(True,True,False,False)
奇数(True,False,False,False)
大写(False,False,True,False)
小写(False,False,False,True)

>> (True,False) > (False,True)
True
>> (1,0) > (0,1)
True
>> [True,False] > [False,True]
True
>> [True,False] > [True]
True

>> [True,False] > [1]
True
>> [True,False] > [3]
False

字典常用内置函数:
dict.get()
获取字典值,不存在返回None

>> d
{-1: 100, -2: 200, 0: 300, -3: 200}

>> d.get("a")
>> print(d.get("a"))
None
>> d.get(-1)
100

指定找不到的返回值

>> d.get("a","not found")
‘not found‘

dict.setdefault(key,value)
key值不存在,增加一个键值对,返回value值
在的话,直接返回value值

>> d.setdefault(-2,10)
200

>> d
{-1: 100, -2: 200, 0: 300, -3: 200}

>> d.setdefault(200,200)
200
>> d
{-1: 100, -2: 200, 0: 300, -3: 200, 200: 200}

小练习:生成一个字典,key 是26个小写字母a-z,value是她的acsii码
方式1:

d = {}

for k in range(97,123):
d[chr(k)] = k

print(d)

方式2:

>> {chr(i):i for i in range(97,123)}
{‘a‘: 97, ‘b‘: 98, ‘c‘: 99, ‘d‘: 100, ‘e‘: 101, ‘f‘: 102, ‘g‘: 103, ‘h‘: 104, ‘i‘: 105, ‘j‘: 106, ‘k
‘: 107, ‘l‘: 108, ‘m‘: 109, ‘n‘: 110, ‘o‘: 111, ‘p‘: 112, ‘q‘: 113, ‘r‘: 114, ‘s‘: 115, ‘t‘: 116, ‘u
‘: 117, ‘v‘: 118, ‘w‘: 119, ‘x‘: 120, ‘y‘: 121, ‘z‘: 122}
>>

判断元素是否存在字典

>> -1 in d
True

dict.update({key:value})
更新字典元素
若key 不存在 增加元素
存在 更新value的值

>> d = {"a":1,"b":2,"c":3}
>> d.update({"d":4})
>> d
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}

>> d.update({"a":"x"})
>> d
{‘a‘: ‘x‘, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}

dict.pop(key)
返回键对应的值并删除键值对

>> d
{‘a‘: ‘x‘, ‘b‘: 2}
>> d.pop("a")
‘x‘
>> d.pop(4,"not found")
‘not found‘

dict.popitem()
随机删除并返回键值对

>> d3
{‘one‘: 1, ‘two‘: 2}
>> d3.popitem()
(‘two‘, 2)
>> d3
{‘one‘: 1}

以上是关于python学习_18的主要内容,如果未能解决你的问题,请参考以下文章

python 机器学习有用的代码片段

学习笔记:python3,代码片段(2017)

Python snippet(代码片段)

学习总结2019.4.18

python学习_18

python 片段18