美文网首页
2018-10-10 Python26 集合set

2018-10-10 Python26 集合set

作者: 孟媛的笔记 | 来源:发表于2018-10-10 22:03 被阅读0次
    • 元祖(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]
    

    相关文章

      网友评论

          本文标题:2018-10-10 Python26 集合set

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