python集合

Posted 冥思苦想

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python集合相关的知识,希望对你有一定的参考价值。

set

无序的不重复的元素

定义

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}

增加

add()

添加一个元素

s1 = set()
s1.add('hello')
s1.add('小猪佩奇')
s1.add('lucy')
print(s1)
{'lucy', '小猪佩奇', 'hello'}

update()

可以添加多个元素

t1 = ('林志玲','言承旭')
s1.update(t1)
print(s1)
{'lucy', '林志玲', '小猪佩奇', 'hello', '言承旭'}

删除

remove()

指定元素删除
删除不存在的元素时,会报错

s1.remove('言承旭')
print(s1)
{'lucy', 'hello', '小猪佩奇', '林志玲'}

pop()

随机删除一个元素
一般删除第一个元素

s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.pop()
print(s1)
s1.pop()
print(s1)
{'小猪佩奇', '林志玲', 'lucy'}
{'林志玲', 'lucy'}

clear()

清空集合

s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.clear()
print(s1)
set()

dicard()

类似remove()
在移除不存在的元素时,不会报错
无返回值

s1 = {'lucy', 'hello', '小猪佩奇', '林志玲'}
s1.discard('言承旭')
print(s1)
{'小猪佩奇', 'lucy', '林志玲', 'hello'}

符号操作

不支持+*

==和in

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集合的主要内容,如果未能解决你的问题,请参考以下文章

金蝶handler中 collection 代码片段理解

Alfred常见使用

比较 C# 中的字符串片段并从集合中删除项目

带有红宝石集合/可枚举的酷技巧和富有表现力的片段[关闭]

常用python日期日志获取内容循环的代码片段

python 有用的Python代码片段