简体   繁体   中英

How to add up the specific values of the OrderedDic elements of a list?

If there is:

random_list = [OrderedDict([('num1',1.0), ('num2', 2.0), ('num3', 3.0)]),OrderedDict([('num1',10.0), ('num2', 20.0), ('num3', 30.0])]
  1. How to add up the values of num2 together? (2.0 + 20.0 = 22.0)
  2. How to add up the values of num2 and num3 together? (2.0 + 20.0 + 3.0 + 30.0= 55.0)

In none of the above, sum() should be used.

Thanks.

You work with OrderedDict like with standard Python's dict:

from collections import OrderedDict

random_list = [OrderedDict([('num1',1.0), ('num2', 2.0), ('num3', 3.0)]),OrderedDict([('num1',10.0), ('num2', 20.0), ('num3', 30.0)])]

case1 = sum(d['num2'] for d in random_list)
print(case1)

case2 = sum(d['num2'] + d['num3'] for d in random_list)
print(case2)

Prints:

22.0
55.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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