简体   繁体   English

从其他列表python的平均值制作新列表

[英]Making new list from average values of other lists python

I'm trying to find an average line from three datasets. 我正在尝试从三个数据集中找到一条平均线。 I have this block of code to make a new list containing the averages of the three other lines. 我有这段代码来制作一个包含其他三行平均值的新列表。

for i in range(0,len(y1)):
    sum=y1[i]+y2[i]+y3[i]
    sum=sum/3
    average.append(sum)

However this block of code for some reason is not outputting the correct averages of 但是,由于某些原因,此代码块未输出正确的平均值

y1[i]+y2[i]+y3[i].

For example the last value of lists y1,y2,y3 are 41.72104029, 39.29410479, and 39.24708382. 例如,列表y1,y2,y3的最后一个值为41.72104029、39.29410479和39.24708382。 However this for loop will say the averages of these three is 30.729766933333334. 但是,此for循环将说这三个的平均值为30.729766933333334。

Any help appreciated! 任何帮助表示赞赏!

I would do this loop differently: 我将以不同的方式执行此循环:

for k in zip(y1, y2, y3):
    average.append(sum(k) / 3.0) # or, float(len(k)) instead of 3.0

This does not mean there is anything wrong with your loop. 这并不意味着您的循环有任何问题。 Most likely the data are not at positions where you expect them to be. 数据很可能不在您期望的位置。 So, I think your problem is in data - not in the loop. 因此,我认为您的问题出在数据上-不在循环中。

For 对于

x = [1, 2, 41.72104029]
y = [3, 6, 39.29410479]
z = [1, 8, 39.24708382]

I get: 我得到:

[1.6666666666666667, 5.333333333333333, 40.08740963333333]

Another variation: 另一个变化:

average = [sum(k) / 3.0 for k in zip(x, y, z)]

Use map: 使用地图:

average = map( lambda *args: sum(args)/float(len(args)), y1, y2, y3)

This way will work for any amount of variables, you can wrap it into a function: 这种方法适用于任何数量的变量,您可以将其包装到一个函数中:

def listAverages(*args):
    return map( lambda *largs: sum(largs)/float(len(largs)), *args)

Here you have a live example 这里有一个现场例子

Found the answer. 找到了答案。 It wasn't in the loop but was rather in the data. 它不是在循环中,而是在数据中。 The lists y1,y2, and y3 were different lengths and so the data was all out of whack. 列表y1,y2和y3的长度不同,因此数据完全不合理。 I used this snippet of code rather to fix the lengths and it works fine. 我使用此代码段来固定长度,并且效果很好。

y1 = y1[len(y1)-232:]
y2 = y2[len(y2)-232:]
y3 = y3[len(y3)-232:]

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

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