zoukankan      html  css  js  c++  java
  • python双向字典

    bidict模块通过一对一映射结构的处理,利用python的切片功能。
     
    模块提供三个类来处理一对一映射类型的一些操作
    'bidict', 'inverted', 'namedbidict'
    >>> import bidict
    >>> dir(bidict)
    ['MutableMapping', '_LEGALNAMEPAT', '_LEGALNAMERE', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bidict', 'inverted', 'namedbidict', 're', 'wraps']
     
    bidict类:用法
    >>> from bidict import bidict
    >>> D=bidict({'a':'b'})
    >>> D['a']
    'b'
    >>> D[:'b']
    'a'
    >>> ~D                #反转字典
    bidict({'b': 'a'})
    >>> dict(D)        #转为普通字典
    {'a': 'b'}
    >>> D['c']='c'     #添加元素,普通字典的方法都可以用
    >>> D
    bidict({'a': 'b', 'c': 'c'}) 
     
    inverted类,反转字典的键值
    >>> seq = [(1, 'one'), (2, 'two'), (3, 'three')]
    >>> list(inverted(seq))
            [('one', 1), ('two', 2), ('three', 3)]

    namedbidict(mapname, fwdname, invname):用法

    >>> CoupleMap = namedbidict('CoupleMap', 'husbands', 'wives')
    >>> famous = CoupleMap({'bill': 'hillary'})
    >>> famous.husbands['bill']
    'hillary'
    >>> famous.wives['hillary']
    'bill'
    >>> famous.husbands['barack'] = 'michelle'
    >>> del famous.wives['hillary']
    >>> famous
    CoupleMap({'barack': 'michelle'})
  • 相关阅读:
    Number Clicker CodeForces
    We Need More Bosses CodeForces
    Tree Constructing CodeForces
    Berland and the Shortest Paths CodeForces
    Allowed Letters CodeForces
    Military Problem CodeForces
    FFT自看
    Communication System
    Dollars
    Coin Change
  • 原文地址:https://www.cnblogs.com/luobuda/p/bidict.html
Copyright © 2011-2022 走看看