I have the following list:
JavaScript
x
10
10
1
mylist: [[(5, 1, 11), (5, 2, 13), (5, 3, 26),
2
(3, 1, 60), (3, 2, 40), (3, 3, 70),
3
(6, 1, 30), (6, 2, 80), (2, 3, 80)],
4
[(5, 1, 7), (5, 2, 8), (5, 3, 6),
5
(3, 1, 50), (3, 2, 44), (3, 3, 44),
6
(6, 1, 20), (6, 2, 40), (2, 3, 50)],
7
[(5, 1, 22), (5, 2, 18), (5, 3, 60),
8
(3, 1, 10), (3, 2, 20), (3, 3, 30),
9
(6, 1, 60), (6, 2, 20), (2, 3, 30)]]
10
I want to calculate the average of the items which have the same “first and the second elements”. E.g., from the below example, I want to take the average of the elements which have ‘5’ and ‘1’ in the first two elements of the list. So, my desired output should be like this:
JavaScript
1
5
1
output: [(5, 1, 13.3), (5, 2, 25.6), (5, 3, 30.6),
2
(3, 1, 40), (3, 2, 34.6), (3, 3, 48),
3
(6, 1, 36.6), (6, 2, 46.6), (6, 3, 56.6)]
4
5
If I have only two items in the lists like:
JavaScript
1
3
1
mylist: [[(1, 11), ( 2, 13), ( 3, 26),
2
[( 1, 60), ( 2, 40), ( 3, 70)], ]
3
I could easily calculate the average by the below code:
JavaScript
1
2
1
np.mean(mylist, axis=0)
2
Advertisement
Answer
see below
JavaScript
1
19
19
1
from collections import defaultdict
2
3
lst = [[(5, 1, 11), (5, 2, 13), (5, 3, 26),
4
(3, 1, 60), (3, 2, 40), (3, 3, 70),
5
(6, 1, 30), (6, 2, 80), (2, 3, 80)],
6
[(5, 1, 7), (5, 2, 8), (5, 3, 6),
7
(3, 1, 50), (3, 2, 44), (3, 3, 44),
8
(6, 1, 20), (6, 2, 40), (2, 3, 50)],
9
[(5, 1, 22), (5, 2, 18), (5, 3, 60),
10
(3, 1, 10), (3, 2, 20), (3, 3, 30),
11
(6, 1, 60), (6, 2, 20), (2, 3, 30)]]
12
13
data = defaultdict(list)
14
for ex_entry in lst:
15
for in_entry in ex_entry:
16
data[(in_entry[0], in_entry[1])].append(in_entry[2])
17
for key, value in data.items():
18
print(f'{key} -> {sum(value) / len(value)}')
19
output
JavaScript
1
10
10
1
(5, 1) -> 13.333333333333334
2
(5, 2) -> 13.0
3
(5, 3) -> 30.666666666666668
4
(3, 1) -> 40.0
5
(3, 2) -> 34.666666666666664
6
(3, 3) -> 48.0
7
(6, 1) -> 36.666666666666664
8
(6, 2) -> 46.666666666666664
9
(2, 3) -> 53.333333333333336
10