标签:交集 python add date enc 存在 discard 重复 增加
无序的不重复的元素
定义
s1 = set()
s2 = {1,3,7}
print(type(s1),type(s2))
<class 'set'> <class 'set'>
应用
将一个列表快速去重
list1 = [3,5,1,5,7,8,9,4,9,8,5,7,4]
s3 = set(list1)
print(s3)
{1, 3, 4, 5, 7, 8, 9}
添加一个元素
s1 = set()
s1.add('hello')
s1.add('小猪佩奇')
s1.add('lucy')
print(s1)
{'lucy', '小猪佩奇', 'hello'}
可以添加多个元素
t1 = ('林志玲','言承旭')
s1.update(t1)
print(s1)
{'lucy', '林志玲', '小猪佩奇', 'hello', '言承旭'}
指定元素删除
删除不存在的元素时,会报错
s1.remove('言承旭')
print(s1)
{'lucy', 'hello', '小猪佩奇', '林志玲'}
随机删除一个元素
一般删除第一个元素
s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.pop()
print(s1)
s1.pop()
print(s1)
{'小猪佩奇', '林志玲', 'lucy'}
{'林志玲', 'lucy'}
清空集合
s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.clear()
print(s1)
set()
类似remove()
在移除不存在的元素时,不会报错
无返回值
s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.discard('言承旭')
print(s1)
{'小猪佩奇', 'lucy', '林志玲', 'hello'}
不支持+*
set1 = {2,3,4,5}
set2 = {2,3,4,5}
print(set2 == set1)
print(4 in set1)
True
True
符号-和difference的作用是一样的
set1 = {2,3,4,5}
set2 = {2,3,4,5,6,7}
set3 = set2 - set1
set4 = set2.difference(set1)
print(set3)
print(set4)
{6, 7}
{6, 7}
set2 = {2,3,4,5}
set1 = {2,3,4,5,6,7}
set3 = set2 & set1
set4 = set2.intersection(set1)
print(set3)
print(set4)
{2, 3, 4, 5}
{2, 3, 4, 5}
set2 = {2,3,4,5}
set1 = {2,3,4,5,6,7}
set3 = set2 | set1
set4 = set2.union(set1)
print(set3)
print(set4)
{2, 3, 4, 5, 6, 7}
{2, 3, 4, 5, 6, 7}
找出两个列表的不同元素
set2 = {2,3,4,5}
set1 = {4,5,6,7}
set3 = set2 ^ set1
print(set3)
set4 = set2.symmetric_difference(set1)
print(set4)
{2, 3, 6, 7}
{2, 3, 6, 7}
标签:交集 python add date enc 存在 discard 重复 增加
原文地址:https://www.cnblogs.com/inmeditation/p/12302709.html