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

Time:09-11

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

[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'

CodePudding user response:

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]

CodePudding user response:

In a single pass:

data  = [
    (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))
    ]


first, second, third = 0, 0, 0
length = 0

for tup in data:
    first    =  tup[1][0]
    second   =  tup[1][1]
    third    =  tup[1][2]
    length   =  1


result = (first/length, second/length, third/length)
  • Related