Home > database >  Conditionally combine or delete tuples in list
Conditionally combine or delete tuples in list

Time:10-08

I have a list of data in Python of the form [(x0, f0), ..., (xn, fn)], where the tuple (xi, fi) represents the location and magnitude, respectively, of the ith element. For example:

point_forces = [(0, 4), (3.5, 2), (0, -3.1), (4, 6), (2, 0), (3.5, -4)]

What is a good way to remove tuples where fi = 0 and combine fi fj of tuples where xi = xj, returning a result in the form [(x0, f0), ..., (xm, fm)]? Continuing the example, this is what I want to get:

result = [(0, 0.9), (3.5, -2), (4, 6)]

The order in which these operations are applied or the order in which tuples appear in the resultant list does not matter to me as long as xi ≠ xj and fi ≠ 0 for all i, j in [0, m].

CodePudding user response:

Try:

out = {}
for x, f in point_forces:
    if f != 0.0:
        out[x] = out.get(x, 0)   f

out = [(x, round(f, 2)) for x, f in out.items() if f != 0.0]  # if you want to keep the resulting tuples where f=0 then remove the if... part
print(out)

Prints:

[(0, 0.9), (3.5, -2), (4, 6)]
  • Related