[Tutor] Summing part of a list

Matthew Webber m_webber_sydney at yahoo.com.au
Tue May 9 18:21:38 CEST 2006


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.

Thanks
Matthew





More information about the Tutor mailing list