[Tutor] Summing part of a list
Bob Gailer
bgailer at alum.rpi.edu
Tue May 9 18:56:23 CEST 2006
Matthew Webber wrote:
> 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
>
Do you mean less than 4? That's how your example works.
> 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?
cnt = 0
for pos, item in enumerate(yourList[::-1]):
if item[1] >= 4: break
cnt += item[1]
yourList = yourList[:len(yourList)-pos] + (u'OTHER', cnt)
> 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
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list