zoukankan      html  css  js  c++  java
  • set 集合数据类型

    set 数据类型

    • set 与列表类似,区别在于 set 不能包含重复的值。
    In [1]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    
    In [2]: b = set(a_list)
    
    In [3]: b
    Out[3]: {'a', 'b', 'c', 'd', 'm', 'n'}
    
    In [4]: type(b)
    Out[4]: set
    
    • set 获取重复的元素
    In [7]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    
    In [8]: b = set([i for i in a_list if a_list.count(i) > 1])
    
    In [9]: b
    Out[9]: {'b', 'n'}
    
    • set 为集合,集合可取交集,集合运算很快,性能很好
    In [10]: a_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    
    In [11]: b_list = ['a', 'c']
    
    In [12]: c = set(a_list).intersection(set(b_list))
    
    In [13]: c
    Out[13]: {'a', 'c'}
    

    set 类型调用 intersection 取2个集合的交集

    • set 为集合,集合可取差集,集合运算很快,性能很好
    In [20]: a_set = set(['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'])
    
    In [21]:  b_set = set(['a', 'c', 'f', 'g'])
    
    In [22]: b_set.difference(a_set)
    Out[22]: {'f', 'g'}
    

    set 类型调用 difference, 获取元素在 b_set 不在 a_set 的数据

  • 相关阅读:
    LeetCode Count Primes
    LeetCode Isomorphic Strings
    126. Word Ladder II
    131. Palindrome Partitioning
    146. LRU Cache
    [LintCode] 574 Build Post Office II
    297. Serialize and Deserialize Binary Tree
    133. Clone Graph
    261. Graph Valid Tree
    [LintCode] 598 Zombie in Matrix 解题报告
  • 原文地址:https://www.cnblogs.com/ronky/p/9815244.html
Copyright © 2011-2022 走看看