• Python:集合


    set集合:

    特点:无序,元素不重复

    功能:关系测试,去重

    集合创建:

    >>> s  = set('python')   
    >>> s
    {'p', 't', 'y', 'h', 'o', 'n'}
    
    >>> l1 = ['python','pingy']
    >>> s = set(l1)
    >>> s
    {'pingy', 'python'}
    
    >>> s = set('hello')
    >>> s    
    {'h', 'e', 'l', 'o'}     #'hello'中有两个'l',集合会去掉重复的元素。

    集合修改:

    .add:增加元素

    .update:更一个新集合到另外一个集合

    >>> s = set('python')
    >>> s
    {'p', 't', 'y', 'h', 'o', 'n'}
    >>> s.add('abc')     #增加元素
    >>> s
    {'p', 't', 'y', 'abc', 'h', 'o', 'n'}
    
    >>> s.update('bcd')  
    >>> s
    {'p', 't', 'y', 'abc', 'c', 'b', 'd', 'h', 'o', 'n'}
    
    >>> se = set('linux')
    >>> se
    {'i', 'x', 'u', 'l', 'n'}
    >>> s.update(se)   #把se集合更新到s集合中
    >>> s
    {'p', 'u', 't', 'y', 'x', 'abc', 'c', 'b', 'd', 'i', 'h', 'l', 'o', 'n'}

    集合删除:

    .remove:删除指定元素

    del:删除整个集合

    .pop:随机删除一个元素

    .clear:清空集合

    >>> s
    {'p', 'u', 't', 'y', 'x', 'abc', 'c', 'b', 'd', 'i', 'h', 'l', 'o', 'n'}
    >>> s.remove('abc')    #删除指定元素
    >>> s
    {'p', 'u', 't', 'y', 'x', 'c', 'b', 'd', 'i', 'h', 'l', 'o', 'n'}
    
    >>> se
    {'i', 'x', 'u', 'l', 'n'}
    >>> del se      #删除集合
    >>> s1
    {'a', 'm', 'n'}
    >>> s1.clear()   #清空集合
    >>> s1
    set()

    集合类型操作:

    in  not in:

    ==  !=

    < >

    >>> s1
    {'a', 'm', 'n'}
    >>> s2
    {'a', 'm', 'o', 'w', 'n'}
    >>> s1<s2
    True

    &:交集

    |:并集

    -:差集

    ^:对称差集(去掉两个集合中的交集,留下剩下的元素的集合)

    >>> s1
    {'a', 'm', 'n'}
    >>> s2
    {'a', 'm', 'o', 'w', 'n'}
    >>> s1<s2
    True
    >>> s1 & s2   #交集
    {'a', 'm', 'n'}
    >>> s1 | s2    #并集
    {'w', 'a', 'm', 'o', 'n'}
    >>> s2 -s1   #差集
    {'w', 'o'}

    例:列表去重

    >>> l = [1,2,3,4,5,6,4,3,6,7,9,12,2]
    >>> l
    [1, 2, 3, 4, 5, 6, 4, 3, 6, 7, 9, 12, 2]
    
    >>> list(set(l))
    [1, 2, 3, 4, 5, 6, 7, 9, 12]
  • 相关阅读:
    与众不同 windows phone (50)
    与众不同 windows phone (49)
    重新想象 Windows 8.1 Store Apps (93)
    重新想象 Windows 8.1 Store Apps 系列文章索引
    重新想象 Windows 8.1 Store Apps (92)
    重新想象 Windows 8.1 Store Apps (91)
    重新想象 Windows 8.1 Store Apps (90)
    重新想象 Windows 8.1 Store Apps (89)
    重新想象 Windows 8.1 Store Apps (88)
    重新想象 Windows 8.1 Store Apps (87)
  • 原文地址:https://www.cnblogs.com/ping-y/p/5868687.html
Copyright © 2020-2023  润新知