zaolee_dragon
zaolee_dragon

Reputation: 109

how to add specific elements of a tuple

I have:

([(5,2),(7,2)],[(5,1),(7,3),(11,1)])

I need to add the second elements having the same first element.

output:[(5,3),(7,5),(11,1)]

Upvotes: 0

Views: 89

Answers (2)

Sameer Mirji
Sameer Mirji

Reputation: 2245

Try this code: (Brute force, may be..)

dt = {}
tp = ([(5,2),(7,2)],[(5,1),(7,3),(11,1)])
for ls in tp:
  for t in ls:
    dt[t[0]] = dt[t[0]] + t[1] if t[0] in dt else t[1]
print dt.items()

The approach taken here is to loop through the list of tuples and store the tuple's data as a dictionary, wherein the 1st element in the tuple t[0] is the key and the 2nd element t[1] is the value.
Upon iteration, every time the same key is found in the tuple's 1st element, add the value with the tuple's 2nd element. In the end, we will have a dictionary dt with all the key, value pairs as required. Convert this dictionary to list of tuples dt.items() and we have our output.

Upvotes: 1

mgilson
mgilson

Reputation: 310257

This is a great use-case for collections.Counter...

from collections import Counter
tup = ([(5,2),(7,2)], [(5,1),(7,3),(11,1)])
counts = sum((Counter(dict(sublist)) for sublist in tup), Counter())
result = list(counts.items()) 
print(result)

One downside here is that you'll lose the order of the inputs. They appear to be sorted by the key, so you could just sort the items:

result = sorted(counts.items())

A Counter is a dictionary whose purpose is to hold the "counts" of bins. Counts are cleverly designed so that you can simply add them together (which adds the counts "bin-wise" -- If a bin isn't present in both Counters, the missing bin's value is assumed to be 0). So, that explains why we can use sum on a bunch of counters to get a dictionary that has the values that you want. Unfortunately for this solution, a Counter can't be instantiated by using an iterable that yields 2-item sequences like normal mappings ...,

Counter([(1, 2), (3, 4)])

would create a Counter with keys (1, 2) and (3, 4) -- Both values would be 1. It does work as expected if you create it with a mapping however:

Counter(dict([(1, 2), (3, 4)]))

creates a Counter with keys 1 and 3 (and values 2 and 4).

Upvotes: 1

Related Questions