简体   繁体   English

使用循环计算列表列表中每个第 n 个列表的平均值

[英]calculate the mean of every nth list in a list of lists using a loop

I am trying to calculate the mean of every nth list in a list of lists using a loop.我正在尝试使用循环计算列表列表中每个第 n 个列表的平均值。 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主题标签之间的位是我正在尝试为其编写循环的位,因此如果列表变得更长,我不必在列表时手动更改它

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: Output:

[1.3333333333333333,
 2.0,
 2.3333333333333335,
 3.3333333333333335,
 4.0,
 5.333333333333333,
 5.0,
 5.0]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM