【发布时间】:2020-09-15 20:55:39
【问题描述】:
我正在尝试使用循环计算列表列表中每个第 n 个列表的平均值。 我已经能够在没有循环的情况下这样做,但是当列表列表变长时这样做会很费力。
我很难解释这个所以这里是代码
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()
主题标签之间的位是我正在尝试为其编写循环的位,因此如果列表变得更长,我不必手动更改它
【问题讨论】:
-
你能试着简化你的问题吗?您可以使用一个更简单的示例来说明您想要做什么。
-
是的,当然(标签中的位是我在纠结的):因为列表之间的时间点不同(即列表中的 [0]、[2]、[4] 列表) of lists) , bp 和 ind 位基本上通过将该时间列表中的第一个元素标记为 true 来使第一个时间点相同。然后它取值列表的第一个元素(即列表列表中的 [1]、[3]、[5] 列表)并对它们进行平均,并将平均值附加到“列表”。它循环遍历每个列表的第二个、第三个等元素
-
我只是希望它循环通过 [0] 到 [2] 等,而不必每次都输入它