How to make a list of integers that is the sum of all the integers from a set of lists in a dict?

前端 未结 2 388
渐次进展
渐次进展 2021-01-12 17:30

Let\'s assume I have a created a dict that is made up of n keys. Each key is mapped to a list of integers of a consistent length. What I want to make now is a new list that

相关标签:
2条回答
  • 2021-01-12 18:01

    Depending on your use-case you might want to consider using an adequate library for more general/complex functionality.

    numpy: general scientific computing

    import numpy as np
    
    my_dict = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}
    
    arr = np.array(list(d.values()))
    # [[1 2 3 4]
    #  [2 3 4 5]
    #  [3 4 5 6]]
    
    arr.sum(axis=0)
    # [ 6  9 12 15]
    

    pandas: data-analysis toolkit

    import pandas as pd
    
    my_dict = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}
    
    df = pd.DataFrame(my_dict)
    #    a  b  c
    # 0  1  2  3
    # 1  2  3  4
    # 2  3  4  5
    # 3  4  5  6
    
    df.sum(axis=1)
    # 0     6
    # 1     9
    # 2    12
    # 3    15
    
    0 讨论(0)
  • 2021-01-12 18:10

    What you need is to transpose the lists so you can sum the columns. So use zip on the dictionary values (keys can be ignored) and sum in list comprehension:

    in one line:

    total_sum_list = [sum(x) for x in zip(*my_dict.values())]
    

    result:

    [6, 9, 12, 15]
    

    How it works:

    zip interleaves the values. I'm using argument unpacking to pass the dict values are arguments to zip (like zip(a,b,c)). So when you do:

    for x in zip(*my_dict.values()):
        print(x)
    

    you get (as tuple):

    (1, 3, 2)
    (2, 4, 3)
    (3, 5, 4)
    (4, 6, 5)
    

    data are ready to be summed (even in different order, but we don't care since addition is commutative :))

    0 讨论(0)
提交回复
热议问题