even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 2023-04-19 23:53  even_blogs  阅读(20)  评论(0编辑  收藏  举报