tags:

views:

255

answers:

4

I have two lists or more than . Some thing like this:

listX = [('A', 1, 10), ('B', 2, 20), ('C', 3, 30), ('D', 4, 30)]
listY = [('a', 5, 50), ('b', 4, 40), ('c', 3, 30), ('d', 1, 20), 
         ('A', 6, 60), ('D', 7, 70])

i want to get the result that move the duplicate elements like this: my result is to get all the list from listX + listY,but in the case there are duplicated for example the element ('A', 1, 10), ('D', 4, 30) of listX is presented or exitst in listY.so the result so be like this

result = [('A', 7, 70), ('B', 2, 20), ('C', 3, 30), ('D', 11, 100),
          ('a', 5, 50), ('b', 4, 40), ('c', 3, 30), ('d', 1, 20)]

(A, 7, 70) is obtained by adding ('A', 1, 10) and ('A', '6', '60') together

Anybody could me to solve this problem.? Thanks.

+8  A: 

This is pretty easy if you use a dictionary.

combined = {}
for item in listX + listY:
    key = item[0] 
    if key in combined:
        combined[key][0] += item[1]
        combined[key][1] += item[2]
    else:
        combined[key] = [item[1], item[2]]

result = [(key, value[0], value[1]) for key, value in combined.items()]
Daniel Roseman
Curses, beat me to a very similar answer by mere seconds!
SpoonMeiser
it took me a while to understand that he was actually _adding_ values, and not removing duplicates.
NicDumZ
+1  A: 

I'd say use a dictionary:

result = {}
for eachlist in (ListX, ListY,):
    for item in eachlist:
        if item[0] not in result:
            result[item[0]] = item

It's always tricky do do data manipulation if you have data in a structure that doesn't represent the data well. Consider using better data structures.

Lennart Regebro
thank you alots
python
thanks for your tips.
python
+2  A: 

You appear to be using lists like a dictionary. Any reason you're using lists instead of dictionaries?

My understanding of this garbled question, is that you want to add up values in tuples where the first element in the same.

I'd do something like this:

counter = dict(
    (a[0], (a[1], a[2]))
    for a in listX
)

for key, v1, v2 in listY:
    if key not in counter:
        counter[key] = (0, 0)
    counter[key][0] += v1
    counter[key][1] += v2

result = [(key, value[0], value[1]) for key, value in counter.items()]
SpoonMeiser
thanks spoonMeiser.it seem to be a problem with code.
python
A: 

Use dictionary and its 'get' method.

d = {}
for x in (listX + listY):
    y       = d.get(x[0], (0, 0, 0))
    d[x[0]] = (x[0], x[1] + y[1], x[2] + y[2])

d.values()
ThisIsMeMoony