我有一个defaultdict,其中键是一个4元组(gene_region,种类,本体,长度).
循环使用很简单:
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:
...
最佳答案 您必须将所有各种关键元素收集到列表中,然后循环遍历这些元素(最好使用
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()生成相同的组合序列,就像嵌套循环一样.