列表字典的增删改查
Posted 一路向北
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表字典的增删改查相关的知识,希望对你有一定的参考价值。
一、列表:
# 列表的作用:存多个值,可以修改 # hobby = [‘play‘,‘eat‘,‘sleep‘] # # 列表的具体操作 # 查看: # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # f = hobby[2] # 查看hobbyt列表内第二个元素 # print(f) # # 增加(1): # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # hobby.append(元素) # f = hobby.append(‘chenyang‘) # print(f) # # 增加(2) # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # hobby.insert(0,amy) # print(hobby) # # 删除(1): # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # X = hobby.pop(1) #1为需要删除的字符,pop元素可以弹出需要删除的元素 # print(x) # print(hobby) # # 删除(2): # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # X = hobby.remove(1) #1为需要删除的字符,remove为直接删除,无法保留 # print(x) # print(hobby) # # 改: # hobby = [‘play‘,‘eat‘,‘sleep‘,[‘egon‘,‘ysb‘]] # hobby[0]=1 #0代表列表内的索引,1为需要更改的字符 # print(hobby) #
二、字典
# # 字典的作用:key是唯一的,可以存储多个值 # 字典的具体操作 # 查: # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # f = dic1[‘name‘] # 查看hobbyt列表内第一个元素,通过key查找到value # print(f) # # 取:通过key找到value。 # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(dic1.get(‘name‘,None)) #通过key取到value,如果找不到则返回None # # 存:字典内有相应的key就覆盖原来的value,反之新增key、value # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # dic1[‘sex‘] = ‘female‘ # dic1[‘hobby‘] = ‘male‘ # print(dic1) # # 改: # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # dic1.update({‘hobby‘:male,‘sex‘:‘female‘}) # print(dic1) # # 长度:计算字典内所有字典的长度 # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(len(dic1)) # # 包含:查找字典内的key # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(‘name‘ in dic1) # # 输出所有的key和value # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(dic1.items) # for k in dic1: # print(k,dic1[k]) # print(k) # # 方法2 # for k in dic1: # print(k,dic1[k]) # # 输出所有的key # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(dic1.key) # # 输出所有的value # dic1 = {‘name‘:‘chenyang‘,‘age‘:38,‘sex‘:‘male‘} # print(dic1.value)
以上是关于列表字典的增删改查的主要内容,如果未能解决你的问题,请参考以下文章