简体   繁体   English

Python 2.7:在多值字典的列表之间的大小差异中添加零并将其求和

[英]Python 2.7: Add zeros to the size difference between lists of a multi-value dictionary and sum it

I have a multi-valued dictionary and I want to sum whatever the values are there which can be done with我有一个多值字典,我想总结那里可以完成的任何值

for key, value in nai_dictionary.items():
    nai_sum_rate.setdefault('%s' %(key), []).append(np.sum(rate_nai[key], axis=0))

for any nai_sum_rate dictionary, as suggested in this webpage .对于任何nai_sum_rate字典,如本网页中所建议。 However, often times the length of the value lists is not the same.但是,值列表的长度通常是不一样的。

This is the test data on which I'm testing right now这是我现在正在测试的测试数据

time = np.array([1,2,3,4,5,6])
test_dict['a'] = np.array([1,2,3,4,5,6]), np.array([1,2,3,4]), np.array([1,2,3,4,5,6])

What I want to do now, is to put a 0 in place of missing values for (in this case) the second array where there is no value against the time variable values and add them together.我现在想要做的是用0代替(在这种情况下)第二个数组的缺失值,其中没有针对time变量值的值,并将它们加在一起。

In my previous testings, before the nai_sum_rate was a list instead of a dictionary I used the answer provided in this link to sort out the problem with the reference variable time .在我之前的测试中,在nai_sum_ratelist而不是dictionary我使用此链接中提供的答案来解决参考变量time的问题。 I've been trying with the dictionary but to no avail.我一直在尝试使用字典,但无济于事。

The expected sum is预期总和是

3, 6, 9, 12, 10, 12

I solved the problem myself, here is the code that I came up with我自己解决了这个问题,这是我想出的代码

for key, value in nai_dictionary.items():
    i=0
    while i < len(rate_nai[key]):
        for key, value in nai_dictionary.items():
            for index, values in enumerate(rate_nai[key]):
                if len(time) < len(values):
                    diff = len(values) - len(time)
                    rate_nai[values] = values[0:np.array(values).size-diff]
                elif len(time) > len(values):
                    diff = len(time) - len(values)
                    rate_nai['%s' %(key)].pop(index)
                    rate_nai.setdefault(
                        '%s' %(key)).append(np.append(np.array(values), np.zeros(diff)))
        i+=1

It can tackle the problem with any number of values that have a lesser length than the reference variable time .它可以解决长度小于参考变量time任意数量值的问题。

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

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