2018-10-10 Python26 集合set

  • 元祖(tuple):只读
  • 列表(list):增删改查
  • 集合(set):没有重复元素,增删改查
  • 字典(dict)

集合(set)字典(dict) 都用{}表示。

#元祖:只读
In [19]: a = (11,22,33,11,22,33)

In [20]: a
Out[20]: (11, 22, 33, 11, 22, 33)

In [21]: type(a)
Out[21]: tuple

#list:增、删、改、查
In [22]: b = [11,22,33,11,22,33]

In [23]: b
Out[23]: [11, 22, 33, 11, 22, 33]

In [24]: type(b)
Out[24]: list

#set:去重
In [25]: c = {11,22,33,11,22,33}

In [26]: c
Out[26]: {11, 22, 33}

In [27]: type(c)
Out[27]: set

#字典
In [25]: d = {"1":"abc", "2":"def"}

In [26]: d
Out[26]: {'2': 'def', '1': 'abc'}

In [27]: type(d)
Out[27]: dict

 

set 集合:

In [54]: c = {11, 22, 33, 44}

In [53]: c.
c.add                          c.issubset
c.clear                        c.issuperset
c.copy                         c.pop
c.difference                   c.remove
c.difference_update            c.symmetric_difference
c.discard                      c.symmetric_difference_update
c.intersection                 c.union
c.intersection_update          c.update
c.isdisjoint                   

In [53]: help(c.add)   #查看帮助

Help on built-in function add:

add(...) method of builtins.set instance
    Add an element to a set.
    
    This has no effect if the element is already present.

#按q退出帮助

 
 

列表去重

方法一:

In [41]: a = [11,22,33,44,22,11,33]

In [42]: b = []

In [45]: for i in a:
   ....:     if i not in b:
   ....:         b.append(i)
   ....:         

In [46]: b
Out[46]: [11, 22, 33, 44]

方法二:

In [28]: a = [11,22,33,44,22,11,33]

In [48]: c = list(set(a))

In [49]: c
Out[49]: [33, 11, 44, 22]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容