• 技术文章 >后端开发 >Python教程

    python字典支持双向索引吗

    anonymityanonymity2019-06-15 13:20:29原创8302
    Python中的字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,字典是无序的,按键取值。

    字典模块提供三个类来处理一对一映射类型的一些操作

    'bidict', 'inverted', 'namedbidict'

    >>> import bidict
    >>> dir(bidict)
    ['MutableMapping', '_LEGALNAMEPAT', '_LEGALNAMERE', '__builtins__', '__doc__', 
    '__file__', '__name__', '__package__', 'bidict', 'inverted', 'namedbidict', 're', 'wraps']

    1.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'})

    2.inverted类,反转字典的键值

    >>> seq = [(1, 'one'), (2, 'two'), (3, 'three')]
    >>> list(inverted(seq))
        [('one', 1), ('two', 2), ('three', 3)]

    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'})

    以上就是python字典支持双向索引吗的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Python
    上一篇:r语言和python的详细对比 下一篇:python是汇编语言吗
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• 现在学python该学python2还是python3?• python是强类型语言吗• python怎么操作Excel• python代码运行结果的显示
    1/1

    PHP中文网