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

How can I put the average of the values of nested tuples inside a list into a new list?

I have a list that looks like this, but much, much longer (1,000,000+ tuples):

[(1, (226, 242, 195)), (1, (218, 236, 188)), (1, (219, 235, 188)), (1, (220, 236, 187)), (1, (217, 235, 187)), (1, (216, 232, 185)), (1, (216, 234, 184))]

I want to find the average of each value in the nested tuple and move those into a new list, like this:

[[1, [avg of first values, avg of second values, avg of third values]]]

If possible, I also would want to get rid of the leading 1, and simplify the list to

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

[avg of first values, avg of second values, avg of third values]

I’ve looked through all similar questions, but none seem to have the exact answer I’m looking for.

The most common error is

TypeError: unsupported operand type(s) for +: ‘int’ and ‘tuple’

>Solution :

The simplest way:

>>> first_sum = second_sum = third_sum = 0
>>> for _, (first, second, third) in lst:
...     first_sum += first
...     second_sum += second
...     third_sum += third
...
>>> num = len(lst)
>>> [first_sum / num, second_sum / num, third_sum / num]
[218.85714285714286, 235.71428571428572, 187.71428571428572]
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