How to sum the elements of N lists?

前端 未结 3 1889
悲&欢浪女
悲&欢浪女 2020-12-17 03:25

can anybody please give me a hint how to aggregate (sum up) specific elements of multiple lists?

For example I have 20 lists with a similar name pattern, each represe

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 04:10

    Use zip to "combine" lists into single one, then sum elements for each index:

    c_agent_0 = [10.0, 11.0, 12.0, 13.0, 14.0]
    c_agent_1 = [1.1, 12.3, 14.2, 13.2, 14.3]
    c_agent_2 = [1.4, 12.1, 14.5, 13.1, 14.2]
    
    zipped_list = zip(c_agent_0, c_agent_1, c_agent_2)
    
    print zipped_list
    print [sum(item) for item in zipped_list]
    

    prints

    [(10.0, 1.1, 1.4), (11.0, 12.3, 12.1), (12.0, 14.2, 14.5), (13.0, 13.2, 13.1), (14.0, 14.3, 14.2)]
    
    [12.5, 35.4, 40.7, 39.3, 42.5]
    

提交回复
热议问题