You need to group your data by the line:
import itertools
input = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]
new_result = {a:[c for *_, c in b] for a, b in itertools.groupby(sorted(input, key=lambda x:x[0]), key=lambda x:x[0])}
final_result = {a:round(sum(b)/float(len(b)), 2) for a, b in new_result.items()}
Output:
{'line1': 4.25, 'line3': 7.75, 'line2': 7.75}
Edit: simpler option with collections.defaultdict
:
from collections import defaultdict
d = defaultdict(list)
for a, _, b in input:
d[a].append(b)
final_result = {a:round(sum(b)/float(len(b)), 2) for a, b
manpreet
Best Answer
2 years ago
I have to create a function able to calculate the average of products built by various lines of production in a range of time.
EXAMPLE:
I cannot calculate the average of each line because i don't know how to determine the period between two days.
EDIT: I'm sorry, i think i haven't explained the problem well. This is not an actual exam, it's a previous exam given by my professor to train.