Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally combine or delete tuples in list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading