head for grouped data - looking for best practice

Steven Bethard steven.bethard at gmail.com
Sat Mar 12 12:17:31 EST 2005


Harald Massa wrote:
> def getdoublekey(row):
>     return row[0:2]
> 
> for key, bereich in groupby(eingabe,getdoublekey):
>     print "Area:",key
>     for data in bereich:
>         print "--data--", data[2:]

Why don't you just pass a slice to itemgetter?

py> eingabe=[
... ("Stuttgart","70197","Fernsehturm","20"),
... ("Stuttgart","70197","Brotmuseum","123"),
... ("Stuttgart","70197","Porsche","123123"),
... ("Leipzig","01491","Messe","91822"),
... ("Leipzig","01491","Schabidu","9181231"),
... ]
py> from itertools import groupby
py> from operator import itemgetter
py> for key, bereich in groupby(eingabe, itemgetter(slice(0, 2))):
...     print "Area:", key
...     for data in bereich:
...         print  "--data--", data[2:]
...
Area: ('Stuttgart', '70197')
--data-- ('Fernsehturm', '20')
--data-- ('Brotmuseum', '123')
--data-- ('Porsche', '123123')
Area: ('Leipzig', '01491')
--data-- ('Messe', '91822')
--data-- ('Schabidu', '9181231')

STeVe



More information about the Python-list mailing list