zoukankan      html  css  js  c++  java
  • 集合 (set) 与列表 (list) 分类: python 20130118 15:22 292人阅读 评论(0) 收藏

    集合 (set) 与列表 (list)

    set 的 union, intersection,difference 操作要比 list 的迭代要快。因此如果涉及到求 list 交集,并集或者差的问题可以转换为 set 来操作。

    set(list1) | set(list2)

    union

    包含list1和list2所有数据的新集合

    set(list1) & set(list2)

    intersection

    包含list1和list2中共同元素的新集合

    set(list1) - set(list2)

    difference

    在list1中出现但不在list2中出现的元素的集合

    使用dict 和 set 测试成员

    Python dict中使用了 hash table,因此查找操作的复杂度为 O(1),因此对成员的查找访问等操作字典要比 list 更快。

    检查一个元素是在dicitonary或set是否存在,这在Python中非常快的。这是因为dict和set使用哈希表来实现,查找效率可以达到O(1),而 list 实际是个数组,在 list 中,查找需要遍历整个 list,其复杂度为 O(n),因此,如果您需要经常检查成员,使用 set 或 dict做为你的容器。

    >>> mylist = ['a', 'b', 'c'] #Slower, check membership with list: 
    >>> ‘c’ in mylist 
    >>> True 
    >>> myset = set(['a', 'b', 'c']) # Faster, check membership with set: 
    >>> ‘c’ in myset: 
    >>> True


    =====

    例子:

    a1=[1,2,3,2,6]
    a2=[2,4,3,5,3]

    print set(a1) | set(a2)

    print set(a1) & set(a2)

    print set(a1)-set(a2)

    print 1 in set(a1)#(增加预判断条件)可以先判断元素1是否在集合中,如果在,就执行下一步。

  • 相关阅读:
    linux tar.gz zip 解压缩 压缩命令
    VC中获取窗体句柄的各种方法
    CodeForces 377B---Preparing for the Contest(二分+贪心)
    Response.Write具体介绍
    Linux实现字符设备驱动的基础步骤
    Android Bundle类
    Otacle表查询
    android该系统的应用API选择演示版本
    微机原理(2)8086
    大话设计の创建模式
  • 原文地址:https://www.cnblogs.com/think1988/p/4628249.html
Copyright © 2011-2022 走看看