[Tutor] Summing part of a list

Matthew Webber m_webber_sydney at yahoo.com.au
Tue May 9 18:56:43 CEST 2006


To expand on my original posting, I came up with this code which works ok :

count_country_aggregated = [cc for cc in count_country if cc[1]>3]
count_country_aggregated.append(('OTHER',sum([cc[1] for cc in count_country
if cc[1]<=3])))

But it uses 2 list comprehensions (therefore 2 passes of the original list).
Surely there is a neater way. 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Matthew Webber
Sent: 09 May 2006 17:22
To: tutor at python.org
Subject: [Tutor] Summing part of a list

I have a list that looks a bit like this -
 
[(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)]

The list items are tuples, the first item of which is a country code, and
the second of which is a numeric count. The list is guarenteed SORTED in
descending order of the numeric count.

What I need is a list with all the members whose count is less than 3
replaced by a single member with the counts added together. In this case, I
want :
[(u'gbr', 30505), (u'fra', 476), (u'ita', 364), (u'ger', 299),
(u'fin', 6), (u'ven', 6), (u'OTHER', 17)]

Any ideas about neat ways to do this? The simplest way is to just build the
new list with a basic loop over the original list. A slightly more
sophisticated way is to split the original list using a list comprehension
with an IF clause.

I have the feeling that there's probably really neat and more Pythonic way -
there are possibilities like zip, map, itertools. Any hints about what to
look at? Remember that the list is sorted already. If you can point me in
the right direction, I'm sure I can work out the specifics of the code.




More information about the Tutor mailing list