Reputation:
I am trying to calculate the mean of every nth list in a list of lists using a loop. I have been able to do so without a loop, but this will prove laborious to do when the list of lists gets longer.
Im struggling to explain this so heres the code
import numpy as np
import matplotlib.pyplot as plt
list = []
t_r = np.arange(0,8)
i = 0
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
#########################
for t in t_r:
b1 = np.array(a[0]) <= t
b2 = np.array(a[2]) <= t
b3 = np.array(a[4]) <= t
ind1 = [(np.count_nonzero(b1))]
ind2 = [(np.count_nonzero(b2))]
ind3 = [(np.count_nonzero(b3))]
x1 = np.array(a[1])
x_mean1 = x1[ind1]
x2 = np.array(a[3])
x_mean2 = x2[ind2]
x3 = np.array(a[5])
x_mean3 = x3[ind2]
x_mean_list = [x_mean1, x_mean2, x_mean3]
x_average = np.mean(x_mean_list)
list.append(x_average)
#########################
no_of_sim = 3
counter = 0
while counter <= ((no_of_sim*2)-1):
plt.plot(a[counter],a[counter+1], lw = 0.5)
plt.plot(list, color = "black")
plt.plot(x_average)
plt.xlabel('Time (s)')
plt.ylabel('copy no.')
counter += 2
plt.show()
The bit inbetween the hashtags is the bit I'm trying to write a loop for so I don't have to manually change it when the list if lists gets much longer
Upvotes: 1
Views: 139
Reputation: 150735
Your code between the hashes are equivalent to the following:
data = [np.array(x) for x in a[::2]]
idx = [np.array(x) for x in a[1::2]]
lst = [np.mean([x[(d<=t).sum()] for x,d in zip(idx,data)]) for t in t_r ]
Output:
[1.3333333333333333,
2.0,
2.3333333333333335,
3.3333333333333335,
4.0,
5.333333333333333,
5.0,
5.0]
Upvotes: 0
Reputation: 4482
check out this code:
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
i = 0
for li in a:
print("Mean of list at index", i, "is:", sum(li)/len(li))
i += 1
Upvotes: 0