3

我有一个默认字典,其中键是 4 元组(基因区域、物种、本体、长度)。

循环它很简单:

for gene_region, species, ontology, length in result_dict:

但是,我想以嵌套方式对其进行迭代,如下所示:

for gene_region
    for species
        for ontology
            ...

我该怎么做呢?除了首先收集价值之外没有其他方法吗?或者使用下面的 dum-dum 方式:

for gene_region, _, _, _ in result_dict:
    for _, species, _, _ in result_dict:
        ...
4

2 回答 2

5

您必须将所有各种关键元素收集到列表中,然后遍历这些元素(itertools.product()最好使用 )。收集可以通过以下方式完成zip()

from itertools import product

gene_regions, species_plural, ontologies, lengths = zip(*result_dict)

for gene_region, species, ontology, length in product(gene_regions, species_plural, ontologies, lengths):
    # do something with this combo.

product()产生与嵌套循环相同的组合序列。

于 2013-08-05T11:42:46.173 回答
2

我认为您可以考虑将数据重新创建为嵌套字典:

>>> result_dict = {}
>>> result_dict[(1, 2, 3, 4)] = "test"
>>> result_dict[(1, 2, 4, 4)] = "test2"
>>> result_dict
{(1, 2, 3, 4): 'test', (1, 2, 4, 4): 'test2'}

>>> result_dict2 = {}
>>> for (a, b, c, d), k in result_dict.iteritems():
...     result_dict2.setdefault(a, {}).setdefault(b, {}).setdefault(c, {})[d] = k
... 
>>> result_dict2
{1: {2: {3: {4: 'test'}, 4: {4: 'test2'}}}}

然后您可以遍历任何级别的键:

for _, a in result_dict2.iteritems():
    for _, b in a.iteritems():
        for _, c in b.iteritems():
            for _, d in c.iteritems():
                # do something
于 2013-08-05T11:40:32.320 回答