简体   繁体   English

循环遍历多个不同大小的 python 词典

[英]Loop through multiple different sized python dictionaries

I am inheriting the following two python dictionaries from another class我从另一个类继承了以下两个 python 字典

>>> print init_treats
{('001', 0): init_treat_001_0, ('001', 3): init_treat_001_3, ('001', 2): init_treat_001_2, ('002', 0): init_treat_002_0, ('002', 1): init_treat_002_1, ('002', 2): init_treat_002_2, ('002', 3): init_treat_002_3, ('001', 1): init_treat_001_1}

>>> print init_untreats
{'002': init_untreat_002, '001': init_untreat_001}

How can I generate the following?如何生成以下内容?

init_treat_001_0 + init_treat_001_1 + init_treat_001_2 + init_treat_001_3 +
init_untreat_001 == 0


init_treat_002_0 + init_treat_002_1 + init_treat_002_2 + init_treat_002_3 + 
init_untreat_002 == 0

Sort your init_treats keys:init_treats键进行排序:

treats = sorted(init_treats)

now you can use itertools.groupby() to group them on the first part of your key:现在您可以使用itertools.groupby()在您的密钥的第一部分对它们进行分组:

from itertools import groupby
from operator import itemgetter

for untreat, group in groupby(sorted(init_treats), itemgetter(0)):
    # group is now a sorted iterator of keys with the same first value
    if init_untreat[untreat] + sum(map(init_treats.get, group)) == 0:
        # sum of init_treat_n_m + init_untreat_n is 0

Because this uses sorting, this is a O(NlogN) solution (N being the size of the init_treats dictionary)因为这使用排序,所以这是一个 O(NlogN) 解决方案(N 是init_treats字典的大小)

You could use a dictionary for a O(N + K) solution (K being the size of the init_untreats dictionary):您可以将字典用于 O(N + K) 解决方案(K 是init_untreats字典的大小):

sums = init_untreat.copy()
for untreat, id in init_treats:
    sums[untreat] += init_treats[untreat, id]

for untreat, total in sums.items():  # use sums.iteritems() in Python 2
    if total == 0:
        # sum of init_treat_n_m + init_untreat_n is 0

Because K is always smaller than N in your case, asymptotically speaking this is a O(N) algorithm, of course.因为在你的情况下 K 总是小于 N,所以渐近地说这是一个 O(N) 算法,当然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM