Home  >  Article  >  Backend Development  >  Detailed introduction to dictionaries and sets in Python

Detailed introduction to dictionaries and sets in Python

零下一度
零下一度Original
2017-07-21 14:28:131636browse

Dictionaries and collections in Python

映射类型:
    表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引
    与序列不同,映射是无序的,通过键进行索引
        任何不可变对象都可用作字典的键,如字符串、数字、元组等
        包含可变对象的列表、字典和元组不能用作键
        引用不存在的键会引发KeyError异常

1) Dictionary

    dict    {  }    空字典
            { key1:value1,key2:value2,... }
        字典在其它编程语言中又称作关联数组或散列表;

    通过键实现元素存取;无序集合;可变类型容器,长度可变,异构,嵌套
                                                 
    支持的操作:
        len(D)                      返回D中的项目数                       
        D[k]                        返回D中键k的值
        D[k] = x                    将D[k]的值设为x                    
                    >>> d1 = {'x':1,'y':2,'z':3}
                    >>> d1['x']
                    1
                    >>> d1['z']                 通过键索引
                    3   
        del D[k]                    从D中删除D[k]
                    >>> del d1['x']
                    >>> d1
                    {'y': 2, 'z': 3}
        k in D                      如果k是D中的值,则返回True
             
     支持的方法:
        D.clear()                   清除所有元素
        D.copy()                    复制一个副本
                    >>> d1 = {'x':1,'y':2,'z':3}
                    >>> id(d1)
                    45320640
                    >>> d2 = d1.copy()                深复制
                    >>> id(d2)
                    45997776            
                    >>> d3 = d1                       浅复制
                    >>> id(d3)
                    45320640                           d1、d3指向同一对象,d2指向另一对象
        D.get(k[,d])                取得对应键的值,若不存在则返回d(默认为空)
                    >>> d1.get('y')
                    2
        D.has_key(k)                是否存在键值,返回True或False.(仅在pyhton2中使用)
        D.items()                   转换为(key,value)元组组成的列表
                    >>> d1.items()
                    [('y', 2), ('x', 1), ('z', 3)]
                    >>> t1,t2,t3 = d1.items()
                    >>> t1
                    ('y', 2)
                    >>> t2
                    ('x', 1)
                    >>> t3
                    ('z', 3)
                    >>> m1,m2 = {'x':1,'y':2}
                    >>> print m1
                    'y'
                    >>> print m2
                    'x'                                 保存的是键,而不是值!!!
        D.values()                  值列表
                    >>> d1.values()
                    [2, 1, 3]
        D.keys()                    键列表
                    >>> d1.keys()
                    ['y', 'x', 'z']
        D.pop(k[,d])                弹出指定键值,若不指定则会触发异常
                    >>> d1.pop()
                    TypeError: pop expected at least 1 arguments, got 0
                    >>> d1.pop('x')
                    1
                    >>> d1
                    {'y': 2, 'z': 3}
        D.popitem()                  随机弹出    
                    >>> d1.popitem()
                    ('y', 2)
                    >>> d1.popitem()
                    ('z', 3)
                    >>> d1.popitem()               
                    KeyError: 'popitem(): dictionary is empty'               为空时异常
                    >>> d1
                    { }
        D.update(m)                   合并字典
                    >>> d1 = { 'x':1,'y':2,'z':3 }
                    >>> d2={'c':'hello','y':66}
                    >>> d1.update(d2)
                    >>> d1
                    {'y': 66, 'x': 1, 'c': 'hello', 'z': 3}             若键存在则会覆盖,不存在就添加   
        D.iteritems()                   返回一个迭代器对象
                    >>> d1 = { 'x':1,'y':2,'z':3 }
                    >>> i1 = d1.iteritems()
                    >>> i1.next()                   使用next方式遍历每一个元素
                    ('y', 2)
                    >>> i1.next()
                    ('x':1)
                    >>> i1.next()
                    ('z':3)
                    >>> i1.next()
                    StopIteration                   遍历结束后不会重新开始
        D.iterkeys()        ->     an iterator over the keys of D
                    >>> i2 = d1.iterkey()
                    >>> i2.next()
                    'y'
        D.itervalues()      ->      an iterator over the values of D
                    >>> i3 = d1.iterkey()
                    >>> i3.next()
                    2
        D.viewvalues()                              返回类似集合方式的字典(值组成)
                    >>> d1.viewvalues()
                    dict_values([2, 1, 3])
        D.viewitems()       ->      a set-like object providing a view on D's items(键值对)
                    >>> d1.viewitems()
                    dict_items([('y', 2), ('x', 1), ('z', 3)])
        D.viewkeys()        ->      a set-like object providing a view on D's keys
                    >>> d1.viewkeys()
                    dict_keys(['y', 'x', 'z'])
                    
                    >>> d2 = dict(x=1,y=2,z=3)              定义字典另一种方式
                    >>> d2
                    {'y': 2, 'x': 1, 'z': 3}

    补充:zip   返回元组组成的列表
            >>> zip('xyz','123')
            [('x', '1'), ('y', '2'), ('z', '3')]            一一对应生成列表
            >>> zip('xyzm','123')
            [('x', '1'), ('y', '2'), ('z', '3')]            多余项被舍弃
            >>> zip('xyz','123','qer')
            [('x', '1', 'q'), ('y', '2', 'e'), ('z', '3', 'r')]                
            >>> dict(zip('xyz','123'))                      构造字典
            {'y': '2', 'x': '1', 'z': '3'}

2) Collection

  无序排列、可哈希;
  支持集合关系测试
        成员关系测试:
            in
            not in
            迭代
  不支持:索引、元素获取、切片

  集合的类型:  set()    frozenset()
                可变       不可变
  没有特定语法格式,只能通过工厂函数创建   
      例:
            >>> s1=set(1,2,3)                                       
            TypeError: set expected at most 1 arguments, got 3              错误方式
            >>> s1 = set([1,2,3])                                           正确方式
            >>> s1
            set([1, 2, 3])
            >>> type(s1)
            set
  支持的方法和操作:

Detailed introduction to dictionaries and sets in Python

##3) Summary

    如何获取使用帮助:
        获取对象支持使用的属性和方法:dir()
        某方法的具体使用帮助:help(list.pop)
        获取可调用对象的文档字串:print obj.__doc__
        
    容器、类型、对象:
        1、列表、元组、字典字面量可在无换行符下分布在多行内,最后一个字符后可跟逗号(若空则不可使用)    

        2、所有对象都有引用计数(sys模块中getrefcount方法);
                >>> import sys
                >>> s1
                set([1, 2, 3])
                >>> sys.getrefcount(s1)                 查看s1的引用计数
                3
                
        3、列表和字典都支持两种类型的复制操作:浅复制和深复制;深复制可使用copy模块中的deepcopy()实现。
    
        4、Python中的所有对象都是“第一类的”,这意味着使用标识符命名的所有对象都具有相同状态,于是,能够命名所有对象都可以直接当数据进行处理;
    
        5、所有序列都支持迭代;(非负整数的有序集合)
    
        6、所有序列都支持的操作和方法:
            s[i]            索引                s[i:j]      切片            
            s[i:j:stride]   扩展切片            len(s)
            min(s)          max(s)              sum(s)
            all(s)          所有为true          any(s)      任意为true
            s1 + s2: 连接                       s1 * N: 重复
            成员关系判断:
                obj in s1
                obj not in s1
        7、可变序列的操作:
            s[index] = value        元素赋值
            s[i:j] = t              切片赋值
            s[i:j:stride] = t       扩展切片赋值
            del s[index]            元素删除
            del s[i:j]              切片删除
            del s[i:j:stride]       扩展切片删除
        引用计数和垃圾回收:
            所有对象都有引用计数
                给对象分配一个新名称或将其放入一个容器内,其引用计数都会增加
                用del语句或为变量重新赋值时,其引用计数会减少
                sys.getrefcount()可以获得对象的当前引用计数
            一个对象的引用计数器归零时,它将被垃圾收集机制回收

The above is the detailed content of Detailed introduction to dictionaries and sets in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn