[Tutor] detecting a change in a iterable object (list, array, etc.)
kent37 at tds.net
Tue Nov 27 02:33:56 CET 2007
Tim Michelsen wrote:
> would like to ask for your help on the following issue:
> What procedure can I use to detect if there's a change when iterating
> over a list?
> For instance if I want to extract the years 1997 and 1998 from the table
> below and save them into separate files?
A list comprehension will work for this. If data is a list of triples of
(year, month, volume) then this will give you a list of the 1997 triples:
data1997 = [ item for item in data if item==1997 ]
> How do I build the average only on the 1997-year values?
Given the above data1997 list can you do this? Sum the third values and
divide by the length of the list.
> Or how do find out that there is three successive values 3*2 and 3*2 in
> the volume column?
itertools.groupby() is helpful for this. It's a bit tricky to understand
though. Here is an extended example:
Here is an example that shows sequences of values of length 3 or more:
for k, g in itertools.groupby(data, key=key):
g = list(g)
if len(g) > 2:
print k, 'occurs', len(g), 'times'
> I already tried a for-loop in connection with a last_value == current
> value comparison but wasn't successful at all.
If you show us what you have done so far it would be easier to make
More information about the Tutor