Find average (mean) from nested list
The idea is to take the nested Python list, like `[1, [2, 3, [1, 2, 5, 6.7]]]`, and compute the average. Here, the innermost list shrinks to a single value (average of 1, 2, 5, and 6.7), then this value goes to as the single file to the parent list (2, 3, 3.675), and so on. So, on the top level in this example, the mean will be calculated out of 2 numbers: 1 and 2.891.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def flatten_mean(lst: list[int | float | list, ]) -> float: """ Returns mean from list elements. If meets nested list, go recursively to process child list, and returns the mean from it back to the parent list. So, for lst=[1, 2, 3] it returns 2, but for lst=[1, [2, 3]] it returns 1,75 :param lst: input list of int|float elements, or embedded list(s) of the same kind :return: mean of list elements """ total: float = 0.0 for item in lst: if isinstance(item, list): total += flatten_mean(item) else: total += item return total / len(lst) # usage input_list = [1, [2, 3, [1, 2, 5, 6.7]]] average = flatten_mean(input_list) print(average) # 1.94583... (1 + ((2 + 3 + (1, 2, 5, 6.7)/4 )/3 ))/2 |
Related pages
...