Python 用于嵌套字典的迭代器类

Python 用于嵌套字典的迭代器类,python,class,dictionary,iterator,nested-loops,Python,Class,Dictionary,Iterator,Nested Loops,初始情况 假设我们有一个以以下形式存储时间序列数据的字典: 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的类中,如下所示: 类数据: 定义初始化

初始情况

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

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的类中,如下所示:

类数据:
定义初始化(self,输入:dict):
self.data=输入
新数据=数据(dic)
显而易见,此类应存储时间序列数据,并在迭代中返回该数据,以便在某个点进行进一步处理



我的问题

我想让类iterable,意思是
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。数据意味着我只需要字典中最低级别的数组,例如
[0,1,2,…]

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

类数据:
定义初始化(self,输入:dict):
self.dictionary=输入
self.data=[series\u数组用于series\u键,series\u数组在series.items()中用于self.dictionary.items()中的…]
self.index=0
定义(自我):
回归自我
定义下一个(自我):
自索引+=1
返回self.data[self.index-1]
问题1:

Would the list comprehension just point to the data within the dictionary or would it really copy the data?
  • 列表理解会仅仅指向列表中的数据吗 字典还是真的复制数据
这意味着我必须在字典上使用一个正常的迭代,但我想不出一种方法来在
\uuuuuiter\uuuuuuuuuuuu
\uuuuuuuuuu next\uuuuuu
中实现这一点

问题2:

How would I implement this nested dictionary-loop within __iter__and __next__?
  • 如何在
    \uu iter\uuu
    \uu next\uu
    中实现这个嵌套字典循环
请注意,我正在寻找这个具体问题的答案,而不是“为什么不使用发电机”或“为什么不这样/那样做”

问题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__?
您只需要在
\uuuu iter\uuuu
中返回一个迭代器(而不是例如使用列表),在这种情况下,列表中的生成器表达式应该足够了:

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())

我只需要字典中最低级别的数组
,为什么不只存储最低级别的数组而不是嵌套字典呢?如上所述,
“字典仍然是需要的,在本例中数组不是选项”
。除了返回所有时间序列,我还必须能够访问具体的序列(如
dic['M15']['100002'][0]
),谢谢您的快速回复!我太专注于迭代器了,以至于忘了给迭代器提供生成器的可能性…:)