繁体   English   中英

如何在 python 中的另一个列表中迭代一个列表

[英]How to iterate a list within another list in python

我有一个 43 个对象的列表,然后每个 object 包括 75 个点。 这 75 个点中的每一个都显示了一天中的特定时间,我想从这 43 个对象中的每一个中获取该确切时间的标准偏差。 我读到我应该使用嵌套的 for 循环,但它显示了一个零矩阵。 谁能帮我?

y1 = [
    a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
    a11, a12, a13, a14, a15, a16, a17, a18, a19, a20,
    a21, a22, a23, a24, a25, a26, a27, a28, a29, a30,
    a31, a32, a33, a34, a35, a36, a37, a38, a39, a40,
    a41, a42, a43
]

#an example of what 'a' is
a1 = np.array(df1['Level'][33:108])
a2 = np.array(df1['Mlevel'][105:180])

#get the standard deviation
SD = []
for i in range(43):
    for j in range(75):
        SD.append(np.std(y1[i[j]]))

#plot the standard deviation with mean
for i in range(43):
    axs[0].plot(x1, mean_y1 + SD, color='lightblue')
    axs[0].plot(x1, mean_y1 - SD, color='lightblue')

所以基本上我想要的是重复下面的循环j = 0到 75 但它不起作用。

c0 = []
for i in range(43):
    c0.append((y1[i][0]))
print(np.std(c0))

因此,如果有人有兴趣,我想通了,下面的代码可以工作:

#create a list of all the elements (c)
c = []    
for j in range(75):
     for i in range(43): 
         c.append((y1[i][j]))
     
     
#print(c) 

#Get the standard deviation of every 43 points    
start = 0       # First to consider
stop = 3225     # the length of the list c
interval = 43   # chunk size

SD = []
for i in range(start, stop, interval):
    SD.append(np.std(c[i:(i + interval)]))
    
print(SD)

你正在下标

SD.append(np.std(y1[i[j]])) 

但 i[j] 没有意义,因为 i 是一个数字 0,1,2,...,您应该输入

SD.append(np.std(y1[i][j]))

为了访问列表中的列表元素

如果您有一个由所有 75 个元素的元素组成的列表 arrays,您可以将列表转换为适当的数组并向量化标准偏差操作:

y1 = np.array(y1)
sd = np.std(y1, axis=0)

如果您想要每天所有时间的标准偏差,请使用axis=1axis=None用于所有 43 天的所有测量值的标准偏差。

您可以通过以相同方式计算平均值来简化绘图:

my1 = y1.mean(0)
...

    axs[0].plot(x1, my1 + sd, color='lightblue')
    axs[0].plot(x1, my1 - sd, color='lightblue')

暂无
暂无

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

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