【问题标题】:python: efficient way to get an item by numerical index from an OrderedDictpython:通过数字索引从 OrderedDict 获取项目的有效方法
【发布时间】:2020-09-19 13:22:17
【问题描述】:

有没有办法实现下面所示的item 方法的等效方法,它提供相同的功能而无需复制所有数据或循环?所以在这个例子中它会返回('bar', 20)

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def item(self, index):
        return list(self.items())[index]


d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))

【问题讨论】:

标签: python ordereddictionary


【解决方案1】:

你可以试试

from collections import OrderedDict

class MyOrderedDict(OrderedDict):
    name_to_index = {}
    def item(self, index):
        return tuple([self.name_to_index[index], self[self.name_to_index[index]]])

    def __setitem__(self, key, value):
        self.name_to_index[len(self.name_to_index)] = key
        super().__setitem__(key, value)


d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))

输出

('bar', 20)

此代码将在每个赋值中存储索引和键,当您使用索引调用项目时,它将返回索引位置的相关值。

【讨论】:

  • 谢谢。经过反思,不幸的是,我可能没有通过根据我自己的子类来构建这个问题来解决这个问题,因为它实际上是关于如何从现有 OrderedDict 类的 any 实例中提取项目,而不是依赖于填充字典时已覆盖 __setitem__ 等方法。对此表示歉意。我不想通过现在编辑问题来破坏你的答案,但我可能更想到的用例是类外的一些函数,如 def item(dct, index): ...
猜你喜欢
  • 2018-09-13
  • 2015-02-27
  • 2020-03-02
  • 2015-12-20
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多