Conditionally combine or delete tuples in list

Question:

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].

Asked By: naterson

||

Answers:

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)]
Answered By: Andrej Kesely

A solution using defaultdict:

d = defaultdict(float)
for k, v in point_forces:
    d[k] += v
    d[k] = round(d[k], 1)
result = [(k, d[k]) for k in d if d[k] != 0.]

(You can use Decimal for better floating point arithmetic)

Answered By: Jonathan Ciapetti
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.