嵌套字典的迭代器类

马库斯

初始情况

假设我们有一个字典,以以下形式存储时间序列数据:

dic = {'M15': 
        { 
            '100001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            '100002': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
                    ...
        },
        'H1': {
            '200001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            ...
        },
        ...
}

现在,假设该字典存储在名为data的类中,如下所示:

class data:

    def __init__(self, input: dict):
        self.data = input

newData = data(dic)

显而易见的是,此类将存储时间序列数据,并在迭代中将其返回以在某些时候进行进一步处理。



我的问题

我想使该类可迭代,这意味着__next__将迭代字典中的所有数据(即将出现的问题不是关于如何对嵌套字典进行迭代,因此请不要回答此问题)。数据意味着我只需要字典中最低级别的数组,例如[0,1,2,...]

让我们假设字典中的数据非常大-可以容纳在内存中,但不能重复。因此,据我所知,列表理解不是一个选项,因为数据也将存储在除了字典之外的新列表中(在此示例中仍然需要字典,并且数组不是选项)。为了完整起见,这看起来像:

class data:
    def __init__(self, input: dict):
        self.dictionary = input
        self.data  = [series_array for series_key, series_array in series.items() for ... in self.dictionary.items()]
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        self.index += 1
        return self.data[self.index - 1]

问题1:

  • 列表理解会只指向字典中的数据还是真的复制数据?

这意味着我必须在字典上使用常规迭代,但是我无法想到在__iter__和中实现此方法的方法__next__

问题2:

  • 如何在__iter__和中实现此嵌套字典循环__next__

请注意,我正在寻找这个具体问题的答案,而不是“为什么不使用发电机”或“为什么不这样/那样地使用发电机”。

网波

问题1:

Would the list comprehension just point to the data within the dictionary or would it really copy the data?

它将保留对字典中列表的引用

问题2:

How would I implement this nested dictionary-loop within __iter__and __next__?

您只需要返回一个迭代器__iter__(而不是例如包含列表),在这种情况下,列表中的generator表达式就足够了:

class Data:
    def __init__(self, input: dict):
        self.dictionary = input
    def __iter__(self):
        return (series_array for series_key, series_array in series.items() for ... in self.dictionary.items())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章