Python基础
2.2 字典及集合
字典dict,是一个无序,可变容器是有索引的集合,在python中使用花括号来编写,拥有键值对key:value(在其他的语言中也有的叫map),使用的时候,主要通过查找键,来对其值的操作。就像查询字典一样,由于其特殊的查询和修改方法,比使用list快的多,在日常使用过程比较常见。字典的key可以重复,value值可以由字符串,列表,元祖组成。字典的相关函数方法如下思维导图
2.2.1 创建和访问字典数据
# 创建一个空字典
d1 = {}
d2 = dict()
print(d2) # {}
print(d1) # {}
# 利用map创建字典 dict(maping)
m = map(lambda x, y: (x, y), range(1,4), list(range(5, 8)))
d3 = dict(m)
print(d3) # {1: 5, 2: 6, 3: 7}
# 创建和访问字典数据
print(type(dict1)) # <class 'dict'>
# 利用zip函数创建字典
x = [1, 2, 3]
y = ['a', 'b', 'c']
d4 = dict(zip(x, y))
print(d4) # {1: 'a', 2: 'b', 3: 'c'}
# dict.fromkeys() 创建一个字典 fromkeys(*args, **kwargs),
# Create a new dictionary with keys from iterable and values set to value
l1 = ('name', 'age', 'bir')
l2 = ['xiaom', '12']
print(dict.fromkeys(l1,l2))
# dict(iterable) 使用可迭代体来初始化字典
d = {}
# for k, v in enumerate(['a','b,''c']):
for k,v in zip(['d', 'e'], [1, 2]):
d[k] = v
print(d) # {'d': 1, 'e': 2}
# 使用参数进行初始化字典
d = dict(g=2, h=3, i=4)
print(d) # {'g': 2, 'h': 3, 'i': 4}
2.2.2 字典的内部函数
# 内部函数
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
dict2 = {'name': 'eason',
'score': [89, 90, 88],
}
print(dict1.__contains__('age')) # True
dict1.__delitem__('age')
print(dict1) # {'name': 'eason', 'score': [89, 90, 88]}
print(dict1.__eq__(dict2)) # True 判断2个对象的值是否相等
print(dict1.__getattribute__('update')) # <built-in method update of dict object at 0x00000293CDD85C28>
print(dict1.__getitem__('name')) # eason
dict3 ={}
dict3.__init__(x=1,y=2)
print(dict3) # {'x': 1, 'y': 2}
print(len(dict2)) # 2
2.2.3 字典的常用方法
# copy() D.copy() -> a shallow copy of D
dict2 = {'name': 'eason',
'score': [89, 90, 88],
}
dict4 = dict2.copy()
print(dict4) # {'name': 'eason', 'score': [89, 90, 88]}
# clear() D.clear() -> None. Remove all items from D.
dict4 = dict2.copy()
dict4.clear()
print(dict4) # {}
# get(self, key, default=None, /) Return the value for key if key is in the dictionary, else default.
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
print(dict1.get("name")) # eason
# items() D.items() -> a set-like object providing a view on D's items
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
print(dict1.items()) # dict_items([('name', 'eason'), ('age', 18), ('score', [89, 90, 88])])
# pop(...) D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
# If key is not found, d is returned if given, otherwise KeyError is raised
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
dict1.pop('name')
print(dict1) # {'age': 18, 'score': [89, 90, 88]}
# popitem(...) D.popitem() -> (k, v), remove and return some (key, value) pair as a
# 2-tuple; but raise KeyError if D is empty.
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
dict1.popitem() # 推出最后一个item
print(dict1) # {'name': 'eason', 'age': 18}
# setdefault(self, key, default=None, /)
# Insert key with a value of default if key is not in the dictionary.
# Return the value for key if key is in the dictionary, else default.
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
print(dict1.setdefault('email','11@qq.com')) # 11@qq.com
print(dict1.setdefault('email', '22@qq.com')) # 11@qq.com
print(dict1) # {'name': 'eason', 'age': 18, 'score': [89, 90, 88], 'email': '11@qq.com'}
# update(...)
# D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
# If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
# If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
# In either case, this is followed by: for k in F: D[k] = F[k]
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
dict2 = {'email': "230@qq.com"}
dict1.update(dict2)
print(dict1) # {'name': 'eason', 'age': 18, 'score': [89, 90, 88], 'email': '230@qq.com'}
# values(...) D.values() -> an object providing a view on D's values
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
print(dict1.values()) # dict_values(['eason', 18, [89, 90, 88]])
print(dict1['score']) # [89, 90, 88]
for i in dict1['score']:
print(i,end="\t") # [89, 90, 88]
# keys(...) D.keys() -> a set-like object providing a view on D's keys
dict1 = {
'name': 'eason',
'age': 18,
'score': [89, 90, 88]
}
print(dict1.keys()) # dict_keys(['name', 'age', 'score'])
2.2.4 集合
集合set和字典类似,但是不同的是,创建的时候使用set(),而不是大括号{},它是一组key的集合,不存储value。
集合的key是唯一值,是不能重复的,相当字典但是其中的key唯一的,相同的key会被自动过滤。
2.2.4.1 创建集合
# 创建集合
# set() -> new empty set object
s0 = set()
print(s0) # set()
s0 = set({1, 2, 3, 4})
print(s0) # {1, 2, 3, 4}
print(type(s0)) # <class 'set'>
# set(iterable) -> new set object
l1 = ['a', 'b', 'c']
l2 = [1, 2, 3]
s2 = set(zip(l1, l2))
print(s2) # {('b', 2), ('c', 3), ('a', 1)}
2.2.4.2 集合的内部函数
# 集合的内部函数
# __contains__(...) x.__contains__(y) <==> y in x.
s1 = set({1, 2, 3, 4})
print(s1.__contains__(2)) # True
# __len__(self, /) Return len(self).
print(len(s1)) # 4
# __or__(self, value, /) Return self|value.
s3 = set({3, 4})
print(s1.__or__(s3)) # {1, 2, 3, 4}
# __rand__(self, value, /) Return value&self.
print(s1.__and__(s3)) # {3, 4}
# __ror__(self, value, /) Return value|self.
print(s1.__xor__(s3)) # {1, 2}
# __sub__(self, value, /) Return value-self.
print(s1.__sub__(s3)) # {1, 2}
# __rxor__(self, value, /) Return value^self.
print(s1.__xor__(s3)) # {1, 2}
# __ior__()
print(s1.__ior__(s3)) # {1, 2, 3, 4}
# __sizeof__(...) S.__sizeof__() -> size of S in memory, in bytes
print(s1.__sizeof__()) # 456
2.2.4.3 集合的内部方法
# 集合的内部方法
s1 = set({'name', 'age', 'sex'})
# add(...) Add an element to a set. This has no effect if the element is already present.
print(f"s1 = {s1}") # s1 = {'sex', 'age', 'name'}
s1.add('bir')
# copy(...) Return a shallow copy of a set.
s2 = s1.copy()
print(f"s2 = {s2}") # s2 = {'sex', 'age', 'bir', 'name'}
# clear Remove all elements from this set.
s1.clear()
print(f"s1 = {s1}") # s1 = set()
# difference(...) Return the difference of two or more sets as a new set.
# (i.e. all elements that are in this set but not the others.)
print(s2) # {'bir', 'age', 'name', 'sex'}
s3 = {'name', 'bir', 'email', 'sex'}
print(s2.difference(s3)) # {'age'}
print(s3.difference(s2)) # {'email'}
# difference_update(...) Remove all elements of another set from this set.
s2.difference_update(s3)
print(s2) # {'age'}
# discard(...) Remove an element from a set if it is a member.If the element is not a member, do nothing.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = {'name', 'bir', 'email', 'sex'}
s2.discard('age')
print(f"s2 ={s2}") # s2 ={'sex', 'bir', 'name'}
s3.discard('age')
print(f"s3={s3}") # 元素中不存在age,所以什么也不做, s3={'name', 'email', 'sex', 'bir'}
# intersection(...) Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.)
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'bir', 'email', 'name', 'sex'})
print(f"new = {s2.intersection(s3)}") # new = {'bir', 'sex', 'name'} 交集
# intersection_update(...) Update a set with the intersection of itself and another.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s2.intersection_update(s3)
print(f"updates2 = {s2}") # {'bir', 'age', 'sex', 'name'}
# isdisjoint(...) Return True if two sets have a null intersection.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s4 = set({'len'})
print(s2.isdisjoint(s3)) # False 有交集
print(s2.isdisjoint(s4)) # True 没有交集
# issubset(...)Report whether another set contains this set.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s4 = set({'email'})
s5 = set({'bir', 'age'})
print(f"s4是否是s3的子集:{s4.issubset(s3)}") # s4是否是s3的子集:True
print(f"s5是否是s2的子集:{s5.issubset(s2)}") # s45否是s2的子集:True
# issuperset(...) Report whether this set contains another set.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s4 = set({'email'})
s5 = set({'bir', 'age'})
print(f's3是否包含s4:{s3.issuperset(s4)}') # s3是否包含s4:True
# pop(...) Remove and return an arbitrary set element. Raises KeyError if the set is empty.
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s3.pop()
print(s3) # {'email', 'age', 'bir', 'name'}
# s3.clear() # 清空该集合
# s3.pop() # 无法再推出任何Key
# print(s3) # 报错信息为 KeyError: 'pop from an empty set'
# remove(...) Remove an element from a set; it must be a member.
# If the element is not a member, raise a KeyError.
s3 = set({'email', 'bir', 'age', 'name', 'sex'})
s3.remove('bir')
print(s3) # {'age', 'name', 'email', 'sex'}
# s3.remove('adress')
# print(s3) # KeyError: 'adress'
# symmetric_difference(...)
# Return the symmetric difference of two sets as a new set.
# (i.e. all elements that are in exactly one of the sets.)
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'age', 'name', 'sex'})
s4 = s2.symmetric_difference(s3)
s5 = s3.symmetric_difference(s2)
print(s4) # {'email', 'bir'}
print(s5) # {'email', 'bir'}
# symmetric_difference_update(...)
# Update a set with the symmetric difference of itself and another.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'age', 'name', 'sex'})
s2.symmetric_difference_update(s3)
print(s2) # {'bir', 'email'}
# union(...)
# Return the union of sets as a new set.
# (i.e. all elements that are in either set.)
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'age', 'name', 'sex'})
s6 = s2.union(s3)
print(s6) # {'name', 'age', 'email', 'sex', 'bir'}
# update(...)
# Update a set with the union of itself and others.
s2 = set({'bir', 'age', 'name', 'sex'})
s3 = set({'email', 'age', 'name', 'sex'})
s2.update(s3)
print(s2) # {'name', 'email', 'sex', 'bir', 'age'}