python中字典与集合

字典

python字典由一个或多个键:值对组成。其中必须为不可变对象,且该对象不得直接或间接地包含可见对象;可以为任意类型地对象。

字典的创建

字典的键不可以重复,否则后面的键值会覆盖前面的键值

dic = {1:'a','b':[1,2,3]}
print(dic)
#fromkeys函数,将所有第一个参数中的元素依次作为键值创建字典,
#所有键对应的值均为第二个参数指定的对象,默认为None
dic = dict.fromkeys([1,2,3,4,5],[123,456])
print(dic)
{1: 'a', 'b': [1, 2, 3]}
{1: [123, 456], 2: [123, 456], 3: [123, 456], 4: [123, 456], 5: [123, 456]}
字典的增加
print(dic)
dic['c'] = (1,2,3)
print(dic)
#setdefault函数,若原字典中不存在指定键添加给定键、值,值默认为None
add = dic.setdefault('d','abc')
print(dic)
print(add)
{1: 'a', 'b': [1, 2, 3]}
{1: 'a', 'b': [1, 2, 3], 'c': (1, 2, 3)}
{1: 'a', 'b': [1, 2, 3], 'c': (1, 2, 3), 'd': 'abc'}
abc
字典的删除
print(dic)
del dic['c']
print(dic)
#popitem函数,无参,3.6版本以后默认删除最后一个,3.6版本之前随机删除
ret = dic.popitem()
print(dic)
print(ret)
#pop函数,以键为参数,若字典中存在该键则删除该条目并返回该条目的值,
#否则报错(若存在第二个参数返回第二个参数,不报错)
ret = dic.pop('1')
print(dic)
print(ret)
ret = dic.pop('d',"没有该键")
print(dic)
print(ret)
{1: 'a', 'b': [1, 2, 3], 'c': 'p'}
{1: 'a', 'b': [1, 2, 3]}
{1: 'a'}
('b', [1, 2, 3])
{}
a
{}
没有该键
print(dic)
ret = dic.pop('d')
{1: 'a', 'b': [1, 2, 3], 'c': 'p'}
KeyError: 'd'
字典的修改
print(dic)
dic['b'] = 908
print(dic)
#update函数,参数字典,将原字典按指定字典更新或添加
dic.update({'e':123,'d':345})
print(dic)
{1: 'a', 'b': [1, 2, 3], 'c': 'p'}
{1: 'a', 'b': 908, 'c': 'p'}
{1: 'a', 'b': 908, 'c': 'p', 'e': 123, 'd': 345}
字典的遍历
print(dic)
#输出所有键
for i in dic.keys():print(i,end=' ')
else:print()
#输出所有值
for i in dic.values():print(i,end=' ')
else:print()
#输出所有键、值
for i in dic.items():print(i)
else:print()
{1: 'a', 'b': [1, 2, 3], 'c': 'p'}
1 b c 
a [1, 2, 3] p 
(1, 'a')
('b', [1, 2, 3])
('c', 'p')

集合

集合的元素必须是不可变元素,且集合中的元素没有重复,顺序不以输入顺序为准。

集合的创建、删除、添加、遍历
s = {1,3,5,7,9,2,4,6,8,12,3,24}
print(s)
#pop函数删除第一个值,并返回
r = s.pop()
print(s)
print(r)
#remove函数,删除一个指定的值,若值不存在会报错
s.remove(24)
print(s)
#add函数,添加一个值
s.add(35)
print(s)
#update函数,参数为可迭代对象,依次添加到集合中
s.update({'a','b','c'})
print(s)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24}
{2, 3, 4, 5, 6, 7, 8, 9, 12, 24}
1
{2, 3, 4, 5, 6, 7, 8, 9, 12}
{2, 3, 4, 5, 6, 7, 8, 9, 35, 12}
{2, 3, 4, 5, 6, 7, 8, 9, 35, 12, 'b', 'c', 'a'}
集合的运算
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
print(s1 & s2)
print(s1 | s2)
print(s1 - s2)
print(s1 ^ s2)
print(s1 > s2)
print(s1 < s2)
{4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
False
False
集合的冻结
s1 = {3,4,5}
#frozense函数创建冻结的集合,参数可以为列表或集合
s = frozenset(s1)
#冻结的集合为不可变对象,可以作为字典的键
dic = {s:'1'}
print(dic)
{frozenset({3, 4, 5}): '1'}
发布了4 篇原创文章 · 获赞 3 · 访问量 769

猜你喜欢

转载自blog.csdn.net/weixin_39630484/article/details/85718016