简体   繁体   中英

Sum of tuples in python using zip()

  'ABX': [(1, 9)],
  'ABD': [(4, 1)],
  'ABY': [(9, 1), (10, 1), (2, 2)],
  'ABR': [(8, 2), (8, 3)]}

Above is the sample python dictionary, I wanted to get output such that tuple elements in the dictionary should be added and make it has single tuple. Below is the required output

  'ABX': [(1, 1)],
  'ABD': [(4, 1)],
  'ABY': [(21, 4)],
  'ABR': [(16, 5)]}
   }

I tried with below code for element (ABR) in dict0 in python shell

    >>>test = [sum(x) for x in zip([ i for i in dict['ABR'])]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
[ i for i in dict['ABR'] ]

this gives a tuple , how can I iterate in zip() ? Any other solution would be very use full

You can use a dict comprehension with each value produced from a sum of a generator expression:

{k: tuple(sum(t) for t in zip(*l)) for k, l in dict0.items()}

This returns:

{'ABX': (1, 9), 'ABD': (4, 1), 'ABY': (21, 4), 'ABR': (16, 5)}

using basic for loop

import operator
d={ 'ABX': [(1, 9216)],
  'ABD': [(4, 15360)],
  'ABY': [(9, 11264), (10, 1024), (14, 451584)],
  'ABR': [(18, 738304), (9, 369664)]}

Now updating the dictionary with summed values

for k,v in d.items():
    sum_tup =(0,0)
    for i in v:
         sum_tup=tuple(map(operator.add, sum_tup, i))
    d[k]=sum_tup

Output

{'ABD': (4, 15360),
 'ABR': (27, 1107968),
 'ABX': (1, 9216),
 'ABY': (33, 463872)}

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