首页>Program>source

有序字典是非常有用的结构,但是不幸的是,它们仅在 3.1 2.7 .在旧版本中如何使用有序字典?

最新回答
  • 2021-1-12
    1 #

    我在python 2.6上使用pip安装了orderddict

    pip install ordereddict
    

  • 2021-1-12
    2 #

    根据文档,对于Python 2.4或更高版本,应使用此代码. PEP的贡献者之一Raymond Hettinger也提供了一些代码.此处的代码据称可以在2.6和3.0下工作,并且是为该建议而设计的。

  • 2021-1-12
    3 #

    要为不同版本的Python导入OrderedDict类,请考虑以下代码段:

    try:
        from collections import OrderedDict
    except ImportError:
        from ordereddict import OrderedDict
    # Now use it from any version of Python
    mydict = OrderedDict()
    

    早于Python 2.6的版本将需要安装 ordereddict (使用pip或其他方法),但是较新的版本将从内置的collections模块中导入。

  • 2021-1-12
    4 #

    此外,如果情况允许,您可以按照自己的方式编程:

    def doSomething(strInput): return [ord(x) for x in strInput]
    things = ['first', 'second', 'third', 'fourth']
    oDict = {}
    orderedKeys = []
    for thing in things:
        oDict[thing] = doSomething(thing)
        orderedKeys.append(thing)
    for key in oDict.keys():
        print key, ": ", oDict[key]
    print
    for key in orderedKeys:
        print key, ": ", oDict[key]
    

    second : [115, 101, 99, 111, 110, 100]
    fourth : [102, 111, 117, 114, 116, 104]
    third : [116, 104, 105, 114, 100]
    first : [102, 105, 114, 115, 116]

    first : [102, 105, 114, 115, 116]
    second : [115, 101, 99, 111, 110, 100]
    third : [116, 104, 105, 114, 100]
    fourth : [102, 111, 117, 114, 116, 104]

    我想,您也可以在字典中嵌入有序键,因为oDict ['keyList'] = orderedKeys

  • 2021-1-12
    5 #

    也可以尝试 future ,py2-3兼容的代码库:

    安装 future 通过点子:

    pip install future

    导入并使用OrderedDict:

    from future.moves.collections import OrderedDict

  • jquery:JavaScript是多线程的吗?
  • windows:我们如何使用win32程序检查文件是否存在?