Reputation: 11
This is a sample code.
a = ['abc', 1234, 23]
b = ['def', 1234, 24]
c = ['abc', 5678, 23]
d = ['def', 5678, 24]
letters = [a,b,c,d]
I want to store the lists with the same values in the 2nd position of the lists and calculate the average for the 3rd position. For eg:
list_ = ['abc', 'def', 1234, 23.48]
Upvotes: 0
Views: 112
Reputation: 5746
Here is one way to do it, first I extract which unique different value exist in second position, and then I loop on those unique values to compute each time the mean of the values in the third position where the element in second position are equals.
import numpy as np
a = ['abc', 1234, 23]
b = ['def', 1234, 24]
c = ['abc', 5678, 23]
d = ['def', 5678, 24]
letters = [a,b,c,d]
unique_second_value = set([l[1] for l in letters])
for unique in unique_second_value:
avg = np.mean([l[2] for l in letters if l[1] == unique])
print (unique, avg)
Output:
1234 23.5
5678 23.5
Upvotes: 1