user1924884
user1924884

Reputation: 21

Using a loop to check if a value has changed?

I'm totally new to programming, please bear with me. I have a question regarding loops and how to detect changes. My list for example is:

['09/2004', 297294186.0]
['09/2004', 257905788.0]
['09/2004', 768116019.0]
['09/2004', 458513425.0]
['08/2004', 251973518.0]
['08/2004', 265328010.0]
['08/2004', 330020350.0]
['08/2004', 383188410.0]
['08/2004', 487483400.0]
['08/2004', 800294431.0]
['08/2004', 999609680.0]
['08/2004', 1237831666.0]
['08/2004', 2242789646.0]

And I want to find the average for each month. I know how to find that but the only way I can think of doing it is

for i in list:
 if month == '08'
    do average

    if month =='09'
    do average

    if month == '10'
    do average

Is there any way I can do a loop that automatically detects when the month has changed, do the average for that month, and continue automatically, instead of doing a ton of if commands?

Any help is much appreciated

William

Upvotes: 2

Views: 1910

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

using itertools.groupby():

In [7]: from itertools import groupby

In [8]: lis=[['09/2004', 297294186.0],
['09/2004', 257905788.0],
['09/2004', 768116019.0],
['09/2004', 458513425.0],
['08/2004', 251973518.0],
['08/2004', 265328010.0],
['08/2004', 330020350.0],
['08/2004', 383188410.0],
['08/2004', 487483400.0],
['08/2004', 800294431.0],
['08/2004', 999609680.0],
['08/2004', 1237831666.0],
['08/2004', 2242789646.0]]


In [10]: from operator import itemgetter

In [11]: for k,g in groupby(lis,key=itemgetter(0)):
    li=[x[1] for x in g]
    print k,sum(li)/float(len(li))
   ....:     
09/2004 445457354.5
08/2004 777613234.556

If your list isn't sorted then you need to use groupby(sorted(lis),key=itemgetter(0)).

Upvotes: 1

John Demetriou
John Demetriou

Reputation: 4377

If i understand correctly you want to do average only once per month in the list? One way that I can think of is assigning flags. Have an array with flags for each month (for example if all months are included create a boolean array with size 12. That way everytime use the number you read as a position in the array to check if average has been done or not

Upvotes: 0

Blender
Blender

Reputation: 298136

You could make a dictionary out of your months:

from collections import defaultdict

months = defaultdict(list)

for date, number in data:
    month, year = date.split('/')

    months[month].append(number)

Now, months looks like {'08': [1, 2, 3, ...], '09': [5, 6, 7, ...]}. From there, computing the averages is pretty simple:

averages = {m: sum(months[m]) / len(months[m]) for m in months}

Upvotes: 4

Related Questions