[Tutor] Summing part of a list
Matthew Webber
m_webber_sydney at yahoo.com.au
Tue May 9 21:18:20 CEST 2006
Thanks Kent, I liked the generator solution (I knew there had to be
something like that).
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Kent Johnson
Sent: 09 May 2006 17:54
Cc: tutor at python.org
Subject: Re: [Tutor] Summing part of a list
<< snip >>
Hmm, must be generator day today. Here is a generator that does what you
want:
In [1]: data = [(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger',
299),
...: (u'fin', 6), (u'ven', 6), (u'chi', 3), (u'hun', 3), (u'mar', 3),
...: (u'lux', 2), (u'smo', 2), (u'tch', 2), (u'aho', 1), (u'ber', 1)]
In [10]: def summarize(data):
....: sum = 0
....: othersFound = False
....: for item in data:
....: if item[1] > 3:
....: yield item
....: else:
....: sum += item[1]
....: othersFound = True
....: if othersFound:
....: yield ('OTHER', sum)
....:
In [11]: print list(summarize(data))
[(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299), (u'fin',
6), (u'ven', 6), ('OTHER', 17)]
<< snip >>
More information about the Tutor
mailing list