0

I have a list :

A = [[33, 0], [34, 0], [35, 5], [36, 0], [38, 0], [39, 0], [40, 0], [41, 0], [42, 0], [43, 0], [44, 0], [45, 1], [46, 0], [47, 0], [48, 0], [49, 0], [50, 0], [51, 1], [52, 0], [56, 0], [57, 0], [58, 0], [59, 0], [62, 1]]

And a second list :

B = [[35, 1], [35, 2], [35, 1], [35, 2], [35, 0], [45, 7], [51, 0], [62, 0]]

My goal is to create the list C like :

if A[0] = B[0] :
  do A[1] + B[1]

The result should be :

C = [[33, 0], [34, 0], [35, 11], [36, 0], [38, 0], [39, 0], [40, 0], [41, 0], [42, 0], [43, 0], [44, 0], [45, 8], [46, 0], [47, 0], [48, 0], [49, 0], [50, 0], [51, 1], [52, 0], [56, 0], [57, 0], [58, 0], [59, 0], [62, 1]]

Hope it's understanding. I don't know how to write it properly in Python.

5
  • 1
    Could you explain your algorithm for adding the two lists together better? Commented May 15, 2020 at 15:33
  • 1
    Does this answer your question? Python group by Commented May 15, 2020 at 15:34
  • 3
    Why is the third item [35, 11] and not [35, 6] ? Commented May 15, 2020 at 15:34
  • 1
    The two lists have not equal length. And what should happen if A[0]!=B[0]? Commented May 15, 2020 at 15:40
  • 1
    @OmarAflak, it seems he's adding all the B's that have B[0]==35. Some kind of a bucket sum. Commented May 15, 2020 at 15:42

2 Answers 2

1
C=[]
for a in A:
    c = a.copy()
    for b in B:
        if b[0] == a[0]:
            c[1] += b[1]
    C.append(c)

Or, using list comprehensions:

C = [[a[0], a[1] + sum(b[1] for b in B if b[0] == a[0])] for a in A]
Sign up to request clarification or add additional context in comments.

Comments

0

Use a Counter to sum B, then add that to A.

from collections import Counter

d = Counter()
for x, count in B:
    d[x] += count

C = [[y, count+d[y]] for y, count in A]

Afterwards:

>>> C
[[33, 0], [34, 0], [35, 11], [36, 0], [38, 0], [39, 0], [40, 0], [41, 0], [42, 0], [43, 0], [44, 0], [45, 8], [46, 0], [47, 0], [48, 0], [49, 0], [50, 0], [51, 1], [52, 0], [56, 0], [57, 0], [58, 0], [59, 0], [62, 1]]
>>> [c for c in C if c[1] != 0]  # The interesting bits
[[35, 11], [45, 8], [51, 1], [62, 1]]
>>> d
Counter({35: 6, 45: 7, 51: 0, 62: 0})

You could also use defaultdict(int) instead, but I think Counter is the more natural fit here. As well, a defaultdict would be mutated just by looking up a non-existent element (e.g. d[33]), which IMO is not ideal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.