【发布时间】:2010-08-12 03:16:11
【问题描述】:
我有一个具有各种“深度”的 dict 数据结构。 “深度”是指例如: 当 depth 为 1 时,dict 会是这样的:
{'str_key1':int_value1, 'str_key2:int_value2}
当depth为2时,dict会是这样的:
{'str_key1':
{'str_key1_1':int_value1_1,
'str_key1_2':int_value1_2},
'str_key2':
{'str_key2_1':int_value2_1,
'str_key2_2':int_value2_2} }
以此类推。
当我需要处理数据时,现在我正在这样做:
def process(keys,value):
#do sth with keys and value
pass
def iterate(depth,dict_data):
if depth == 1:
for k,v in dict_data:
process([k],v)
if depth == 2:
for k,v in dict_data:
for kk,vv, in v:
process([k,kk],v)
if depth == 3:
.........
所以当 depth 为 n 时,我需要 n 循环。由于深度可以达到 10,我想知道是否有更动态的方式来进行迭代,而不必写出所有 if 和 for 子句。
谢谢。
【问题讨论】:
标签: python algorithm dictionary iteration