简体   繁体   中英

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. However this for loop will say the averages of these three is 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. 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:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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