class collections.OrderedDict([items]) - Return an instance of a dict
subclass, supporting the usual dict methods. An OrderedDict is a dict
that remembers the order that keys were first inserted. If a new entry
overwrites an existing entry, the original insertion position is left
unchanged. Deleting an entry and reinserting it will move it to the
end.
New in version 2.7.
因此,如果你使用的是一个有序的字典,你不会删除键-然后'动物'将永远在你添加的位置-例如索引2。
此外,要获得“猫”的索引,您可以简单地使用:
from collections import OrderedDict
d = OrderedDict((("fruit", "banana"), ("drinks", "water"), ("animal", "cat")))
d.keys()
>>> ['fruit', 'drinks', 'animal']
d.values()
>>> ['banana', 'water', 'cat']
# So
d.values().index('cat')
>>> 2
首先,你需要阅读文档。如果打开一个Python教程,然后尝试查找有关OrderedDict的信息,您将看到以下内容:
因此,如果你使用的是一个有序的字典,你不会删除键-然后'动物'将永远在你添加的位置-例如索引2。
此外,要获得“猫”的索引,您可以简单地使用:
您可以获得具有
keys
属性的键列表:但是,使用
iterkeys()
可以获得更好的性能。对于使用Python 3的用户:
对于Python3:
tuple(d).index('animal')
这几乎与上面Marein的答案相同,但是使用了不可变元组而不是可变列表。所以它应该运行得快一点(在我的快速检查中大约快12%)。
相关问题 更多 >
编程相关推荐