even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  161 随笔 :: 0 文章 :: 5 评论 :: 10万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

1、字典

字典里的数据是以键值对的形式出现,字典数据与数据顺序没有关系,即字典不支持下标,后期无论数据如何变化,只需要按照对应的键的名字查找数据即可

字典的定义

# 有数据的字典
dict1 = {"name": "aaaa", "age": 12}

# 空字典
dict2 = {}

dict3 = dict()

字典的增删改查

复制代码
map = dict()

# 增加数据
map['name'] = 'aaa'
map['age'] = 12

print(map)  # {'name': 'aaa', 'age': 12}

# 修改数据
map['name'] = 'even'

print(map)  # {'name': 'even', 'age': 12}

# 查找数据
print(map['name'])  # even

# 该方法如果有值则返回指定的值,如果没有值则返回None
print(map.get('name'))  # even
print(map.get('fav'))  # None

# 以下三种方法可以进行遍历
print(map.keys())  # dict_keys(['name', 'age'])
print(map.values())  # dict_keys(['name', 'age'])
print(map.items())  # dict_items([('name', 'even'), ('age', 12)])

keys = map.keys()
for item in keys:
    print(item)

values = map.values()
for index, item in enumerate(values):
    print(index, item)

items = map.items()
for key, val in items:
    print(key, val)
# 删除数据
del map['age']
print(map)  # {'name': 'even'}

map.clear()  # 清空map
print(map)  # {}
复制代码
复制代码
d = {"name": "aaa"}

d.update({"age": 12, "name": "bbb"})

print(d) #{'name': 'bbb', 'age': 12}


n = d.pop('name') # 返回的是 “bbb”

print(n)
复制代码

2、集合

集合的创建

创建集合使用{}或者set(), 但是如果要创建空集合只能使用set(), 因为{}是用来创建字典的

collect = {'first', 'second', 'third'}

collect1 = set() # 创建空集合

collect2 = set('test')
print(collect2) # {'e', 't', 's'} 集合中的数据是不能重复的

注意:集合中不能有列表,字典,只能的基础性的数据类型, 以及元组, 集合具有去重的功能

集合追加数据

add(): 追加单个数据

update(list): 接收序列,并且把序列里的数据逐个追加到集合中

复制代码
collect = set()

# 追加单个数据
collect.add('first')
print(collect) # {'first'}

collect.update(['second', 'third', 'fourth'])
print(collect) # {'first', 'second', 'third', 'fourth'}

# 以字符串的形式进行update时,会将字符串拆开进行添加,如果是数值,则会报错
collect.update('abc')
print(collect) # {'third', 'a', 'b', 'first', 'second', 'c', 'fourth'}
复制代码

注意:集合没有顺序

集合数据的删除

remove(): 删除集合中的指定数据, 如果数据不存在则报错

discard(): 删除集合中的指定数据, 如果数据不存在不报错

pop(): 随机删除集合中的某个数据, 并返回这个数据

clear(): 清空整个集合

复制代码
collect = {'first', 'second', 'third', 'fourth', 'fifth', 'sixth'}

collect.remove('first')

collect.discard('second')

print(collect)  # {'third'}

print(collect.pop())  # 返回被删除的随机 sixth

collect.clear()
print(collect)  # set()
复制代码

集合的查找

in, not in

collect = {'first', 'second', 'third', 'fourth', 'fifth', 'sixth'}

print('third' in collect)  # True

print('third' not in collect)  # False

 

posted on   even_blogs  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示