集合

作者: __construct | 来源:发表于2018-08-08 11:06 被阅读0次

特性

  • 唯一性,数据不重复,自动去重
  • 无序
  • 集合可以使用的数据(str, int, float, bool,tuple, complex, frozenset())
  • 不能访问,删除,修改,添加

序列操作

  • in
  • len() 检测集合长度
  • max() 最大值
  • min() 最小值
  • set() 类型改变为集合类型

集合基本操作

  • add() 向集合中添加一个元素
  • pop() 随机删除集合中的值
s = {1, 2, 3, 4, 5}
print( s.pop() )
# 1
print(s)
# {2, 3, 4, 5}
  • remove() 移除集合中指定的值,移除的数据不存在,不报错
  • discard() 移除集合中指定的值,移除的数据不存在,不报错
  • clear() 清空集合
  • copy() 复制集合

集合运算函数

  • difference() 差集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

print( s1.difference(s2) )
# {1, 2, 3, 4}
print( s2.difference(s1) )
# {8, 9, 6, 7}

  • difference_update() 差集更新
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

s1.difference_update(s2)
print(s1)
# {1, 2, 3, 4}
  • intersection() 交集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

print( s1.intersection(s2) )  # {5}
print( s2.intersection(s1) )  # {5}
  • intersection_update() 交集更新
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

s1.intersection_update(s2)
print(s1)
#{5}
  • union() 并集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

print( s1.union(s2) )
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print( s2.union(s1) )
# {1, 2, 3, 4, 5, 6, 7, 8, 9}

*update() 并集更新

s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

s1.update(s2)
print(s1)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
  • issuperset() 超集
  • issubset() 子集
s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9,0 }
s2 = {5, 6, 7, 8, 9}

print( s1.issuperset(s2) ) # True
print( s2.issubset(s1) ) #true
  • isdisjoint() 非相交集合
s1 = {1, 2, 3, 4}
s2 = {6, 7, 8, 9}

print( s1.isdisjoint(s2) )
# True
  • symmetric_difference() 两个集合不想交的集合
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

print( s1.symmetric_difference(s2) )
# {1, 2, 3, 4, 6, 7, 8, 9}
print( s2.symmetric_difference(s1) )
# {1, 2, 3, 4, 6, 7, 8, 9}
  • symmetric_difference_update() 集合不想交更新操作
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}

s1.symmetric_difference_update(s2)
print(s1)
# {1, 2, 3, 4, 6, 7, 8, 9}

冰冻集合 frozenset

可以传入列表

相关文章

  • 我的Swift的学习总结 -->第二周

    集合 集合:Set,定义一个集合可以写成:var 集合名 : Set<集合类型> = [集合元素],具体的集合应用...

  • markdown 测试

    集合 集合 集合 引用

  • kotlin学习第五天:集合,高阶函数,Lambda表达式

    集合 list集合 list集合分为可变集合与不可变集合。由list of创建的集合为不可变集合,不能扩容,不能修...

  • kotlin练习 ---- 集合练习

    kotlin练习 - 集合练习 Set集合 Set集合创建 Set集合的使用 List集合 List集合创建 Li...

  • 集合总结

    集合 集合分为单列集合和双列集合两种: 一.单列集合: Collection是单列集合的顶级接口: 其中有三类集合...

  • 映射、元组、集合

    映射 元组 集合 集合之seq 集合之set 集合之map

  • 16.Collection集合

    主要内容: Collection 集合 迭代器 增强for List 集合 Set 集合 1,集合 集合是java...

  • 集合与有序集合

    集合分为有序集合 (zset) 和无序集合 (set), 一般无序集合也直接说成集合 无序集合 (set) 无序集...

  • python入坑第八天|集合

    好的,各位蛇友,我们今天来学习集合。 内容: 集合的创建 集合操作符号 集合的内置函数 集合的创建 集合用set(...

  • 集合框架

    集合框架的概念 集合:存放数据的容器 集合框架:java中,用于表示集合,以及操作集合的类和接口的统称 数组与集合...

网友评论

      本文标题:集合

      本文链接:https://www.haomeiwen.com/subject/qgbavftx.html