介绍

  在Python set是基本数据类型中的一种集合类型,它有可变集合(set())和不可变集合(frozenset)两种。set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交、差、对称差等。

  sets 支持 x in set、 len(set)、和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列 的操作。

基本操作

  1、集合去重

    list1 = [12,20,12,39,20]

    list2= list(set(list1))

    print list2

    输出:[20,12,39]

  2、集合添加,删除

    a= set('hello')

    a.add('world')

    a.remove('world')

    a = set([1,2,3])

    a.update([4,5,6])

  3、python set() 集合操作符号、数学符号

    python 集合set()

  交集操作:

    a = set('123')

    b = set('345')

    print a & b

    输出:set(['3'])

  并集操作:

    a = set('123')

    b = set('345')

    print a | b

    输出:set(['1', '3', '2', '5', '4'])

  差集操作

    a = set('12358')

    b = set('345')

    print a - b

    输出:set(['1', '8', '2'])

 

 

  

  

 

 

相关文章:

  • 2021-10-11
  • 2021-10-05
  • 2021-11-08
  • 2021-12-09
  • 2021-12-09
  • 2021-08-28
猜你喜欢
  • 2021-06-15
  • 2021-10-21
  • 2022-02-18
  • 2021-08-24
  • 2021-11-11
  • 2021-04-08
相关资源
相似解决方案