day 4 集合

1.集合

In [1]: a = (11,22,33,11,22,33)
In [2]: a
Out[2]: (11, 22, 33, 11, 22, 33)        #元组

In [3]: b = [11,22,33,11,22,33]      
In [4]: b                                          #列表
Out[4]: [11, 22, 33, 11, 22, 33]

In [5]: c = {11,22,33,11,22,33}     #集合
In [6]: c
Out[6]: {11, 22, 33}

#####  集合  去重
In [9]: type(c)
Out[9]: set

 

2.set集合操作

In [12]: s
Out[12]: {11, 22, 33}

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

#### 增删改查
s.add    
s.pop                              
s.remove
s.update

 

 

###  查看帮助文档
In [13]: help(s.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.
(END)

 

 

#### 增add
In [15]: s.add(55)

In [16]: s
Out[16]: {11, 22, 33, 55}

In [17]: s.add(55)

In [18]: s
Out[18]: {11, 22, 33, 55}

 

 

3.面试题:list列表去重

  1) 版本1

a = [11,22,33,11,22,33]
print(a)
b = []
for i in a:
    if i not in b:
        b.append(i)

print(b)

###3  运行结果
[11, 22, 33, 11, 22, 33]
[11, 22, 33]

 

 

 

  2)版本2:set去重

In [1]: a = [11,22,33,11,22,33]

In [4]: s = set(a)    #list列表类型转换为set集合类型

In [5]: s
Out[5]: {11, 22, 33}   #去重

In [6]: a = list(s)   #再转换为list列表

In [7]: a
Out[7]: [33, 11, 22]

 

posted @ 2017-11-26 11:57  venicid  阅读(137)  评论(0编辑  收藏  举报