0

次のエポック時間キーの辞書があるとします。

dict = {
  "1363017884": "some val",
  "1363033813": "another val",
}

1363033000 より大きいすべてのキーを検索したいと思います (この場合、1363033813 のみが一致します)。各キーをチェックする for ループがありますが、これは非常に非効率的です。

for epoch,value in dict.iteritems():
  if int(epoch) >= 1363033000:
    do something interesting
4

3 に答える 3

7

辞書をループすることが唯一の現実的な選択肢であり、これ以上効率的な方法はありません。

または、別のデータ構造を使用することもできます。たとえば、値に接続された整数を btree 構造に格納すると、特定の検索値より大きいまたは小さいキーの検索がはるかに効率的になります。

于 2013-03-11T21:13:07.927 に答える
0

You could slightly modify the code from here to add a large_keys attribute. Now, whenever one of those large epochs gets added, the dict will keep track of them. When you want to iterate over them, you can simply iterate over that attribute.

class MyUpdateDict(dict):
    def __init__(self, *args, **kwargs):
        self.large_keys = []
        self.update(*args, **kwargs)

    def __setitem__(self, key, value):
        # optional processing here
        if int(key)>1363033000:
            self.large_keys.append((key,value))
        super(MyUpdateDict, self).__setitem__(key, value)

    def update(self, *args, **kwargs):
        if args:
            if len(args) > 1:
                raise TypeError("update expected at most 1 arguments, got %d" % len(args))
            other = dict(args[0])
            for key in other:
                self[key] = other[key]
        for key in kwargs:
            self[key] = kwargs[key]

    def setdefault(self, key, value=None):
        if key not in self:
            self[key] = value
        return self[key]

This might be overly simplistic, because the large value is hard-coded, but you can modify to make it a bit more appropriate.

于 2013-03-11T21:36:21.297 に答える