简体   繁体   中英

Calculating average from ith element in list of tuples

Note: I've done edits to the dataset that I think will work better for calculating the average.


My data look like this:

[[2015, 0.23, 0.45, 1.23],
[2014, 1.22, 2.54, 0.98],
[2013, 0.33, 2.11, 0.43],
...]

Where the data are now lists within a list. The first element in the sublist is the year of growth, and the following three floats are the ring widths for that year. My question is this: Is there a way to calculate the average of the last three elements in each sublist, and generate a new list, with just year, average growth that would look something like:

[[2015, 1.58], [2014, 0.956], ...]

Where 1.58 is (1.22 + 2.54 + 0.98)/3 .

Sorry for the confusion before, I'm new to Stack Overflow, and I can tell that more information is better.

Here is the code I have so far:

   for i in list[0]:
      newlist = [(list[1] + list[2] + list[3])/3]

But that doesn't seem to work.

Any help would be appreciated. Thanks!

If your data is in the form:

trees= [[2015, 0.23, 0.45, 1.23],
        [2014, 1.22, 2.54, 0.98],
        [2013, 0.33, 2.11, 0.43]]

You could do:

new_trees=[]

for x in trees:
    average="{0:.2f}".format(sum(x[1:])/len(x[1:]))
    new_trees.append([x[0]]+[average])
                     #year + average 

This would output:

>>> new_trees
[[2015, '0.64'], [2014, '1.58'], [2013, '0.96']]  

@logic has the first correct answer (should be the accepted answer), here's how to do it with a short list comprehension.

trees= [[2015, 0.23, 0.45, 1.23],
        [2014, 1.22, 2.54, 0.98],
        [2013, 0.33, 2.11, 0.43]]

data = [ (x[0], (sum(x[1:]) / len(x[1:])) ) for x in trees]

which yields this list of tuples:

[(2015, 0.6366666666666667), (2014, 1.58), (2013, 0.9566666666666667)]

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