【发布时间】:2009-10-24 05:44:33
【问题描述】:
【问题讨论】:
-
orderedDict 对你有用吗?你能帮忙检查一下我在本页末尾的代码吗
标签: python
【问题讨论】:
标签: python
我用 pip 在 python 2.6 上安装了 ordereddict
pip install ordereddict
【讨论】:
根据documentation,对于Python 2.4 或更高版本应使用this code。还有一些code from Raymond Hettinger,PEP 的贡献者之一。这里的代码声称可以在 2.6 和 3.0 下工作,并且是为提案而编写的。
【讨论】:
要为不同版本的 Python 导入 OrderedDict 类,请考虑以下 sn-p:
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 或其他方法),但较新的版本将从内置的集合模块中导入。
【讨论】:
此外,如果您的情况允许,您可以自行编程:
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]
秒:[115、101、99、111、110、100]
第四:[102、111、117、114、116、104]
第三:[116、104、105、114、100]
第一个:[102、105、114、115、116]首先:[102、105、114、115、116]
第二个:[115、101、99、111、110、100]
第三:[116、104、105、114、100]
第四:[102, 111, 117, 114, 116, 104]
我想你也可以将有序键嵌入到字典中,如 oDict['keyList'] = orderedKeys
【讨论】:
你也可以试试future,py2-3 兼容代码库:
future:pip install future
from future.moves.collections import OrderedDict
【讨论】:
在python2.6中给了我:
$ pip install ordereddict
Could not find a version that satisfies the requirement from (from versions:)
No matching distribution found for from
但是
$ easy_install ordereddict
install_dir /usr/local/lib/python2.6/dist-packages/
Searching for ordereddict
Reading http://pypi.python.org/simple/ordereddict/
Best match: ordereddict 1.1
Downloading https://pypi.python.org/packages/source/o/ordereddict/ordereddict-1.1.tar.gz#md5=a0ed854ee442051b249bfad0f638bbec
Processing ordereddict-1.1.tar.gz
Running ordereddict-1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-lYgPE3/ordereddict-1.1/egg-dist-tmp-GF2v6g
zip_safe flag not set; analyzing archive contents...
Adding ordereddict 1.1 to easy-install.pth file
Installed /usr/local/lib/python2.6/dist-packages/ordereddict-1.1-py2.6.egg
Processing dependencies for ordereddict
Finished processing dependencies for ordereddict
做了。
【讨论】:
对于那些由于某种原因不能依赖于 pip 的用户,这里有一个 非常糟糕 OrderedDict 的实现(它是不可变的,具有大部分功能,但没有任何性能提升)。
class OrderedDict(tuple):
'''A really terrible implementation of OrderedDict (for python < 2.7)'''
def __new__(cls, constructor, *args):
items = tuple(constructor)
values = tuple(n[1] for n in items)
out = tuple.__new__(cls, (n[0] for n in items))
out.keys = lambda: out
out.items = lambda: items
out.values = lambda: values
return out
def __getitem__(self, key):
try:
return next(v for (k, v) in self.items() if k == key)
except:
raise KeyError(key)
【讨论】: