python2134
python2134

Reputation: 21

Comparing Two Uneven List Tuples

I am trying to compare to list tuples and subtract the second value pair ONLY if the first value matches. After this subtraction is done, I would like to keep the tuples that were not in the list. In this case, I would keep ('2574529422', 1).

The code below that I tried returns an empty list. I don't know why it's not working, if allc[0] should be in stmt[0] when it's iterating??

I tried:

a = [(allc[0], stmt[1]-allc[1]) for allc,stmt in zip_longest(self.allocation_results, self.statement_results)
             if allc[0] in stmt[0]]

input:

List 1

[('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]

List 2

[('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('123456789', 1)]

Expected output:

[('0856547518', 1), ('1292058151', 2), ('2574529422', 2), ('2574529422', 1)]

Upvotes: 0

Views: 80

Answers (2)

quamrana
quamrana

Reputation: 39354

I had to rearrange a few things to get this to work.

I suspect you had some errors you didn't report.

from itertools import zip_longest

ar = [('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]
sr = [('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('2574529422', 1)]

def check(allc, stmt):
    if allc is None:
        return True
    return allc[0] == stmt[0]

def make_tuple(allc, stmt):
    if allc is None:
        return stmt
    return allc[0], allc[1] - stmt[1]

a = [make_tuple(allc, stmt) for allc,stmt in zip_longest(ar, sr) if check(allc, stmt)]

print(a)

Output as required

Upvotes: 0

not_speshal
not_speshal

Reputation: 23146

If the first values of each of your tuples is unique as in your example, you can use them as dictionaries in a list comprehension to get your result:

l1 = [('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]
l2 = [('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('123456789', 1)]

>>> [(k, dict(l1)[k]-dict(l2)[k]) if k in dict(l1) else (k, dict(l2)[k]) for k in dict(l2)]
[('0856547518', 1), ('1292058151', 2), ('2574529422', 2), ('123456789', 1)]

Upvotes: 1

Related Questions