[portland] Still Having List/Tuple Problems

jason kirtland jek at discorporate.us
Wed Apr 16 21:33:22 CEST 2008


Rich Shepard wrote:
> On Wed, 16 Apr 2008, jason kirtland wrote:
> 
>> # option 2) make groups, each sharing a common 'left' item
>> from itertools import groupby
>> from operator import itemgetter
>>
>> for left, grouped in groupby(list_o_tuples, itemgetter(0)):
>>     print left
>>     for left_again, right in grouped:
>>         print "\t", right
>>
>> # look under the hood at what groupby() does in 2)
>> for left, grouped in groupby(list_o_tuples, itemgetter(0)):
>>     print left, list(grouped)
> 
>    Thanks, Jason. I obviously still don't fully understand 'groupedby', but
> This is what I need to create nested for loops.
> 

Maybe implementing the 'itemgetter' and 'groupby' library functions from 
scratch will illuminate them.  'groupby' is just a canned version of the 
option 1) from my last post:

Python 2.5.1 (r251:54863, May 23 2007, 16:25:53)
[GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> def itemgetter(index):
...     def get_it(obj):
...         return obj[index]
...     return get_it
...
 >>> a_list = ['x', 'y', 'z']
 >>> getter = itemgetter(1)
 >>> getter
<function get_it at 0xb7f89c34>
 >>> getter(a_list)
'y'
 >>> getter(['item 0', 'item 1', 'item 2'])
'item 1'
 >>> def groupby(sequence, key_function):
...     results = []
...     current_key, group = None, []
...     for item in sequence:
...         print "considering", item
...         key = key_function(item)
...         if key != current_key:
...             print "new key", key, "starting new group"
...             current_key = key
...             group = []
...             results.append((key, group))
...         print "adding", item, "to group"
...         group.append(item)
...     return results
...
 >>> some_pairs = [('A', 1), ('A', 2), ('B', 1), ('B', 2)]
 >>> for grouped_by, grouping in groupby(some_pairs, itemgetter(0)):
...     print "grouped_by", grouped_by
...     print "grouping", grouping
...
considering ('A', 1)
new key A starting new group
adding ('A', 1) to group
considering ('A', 2)
adding ('A', 2) to group
considering ('B', 1)
new key B starting new group
adding ('B', 1) to group
considering ('B', 2)
adding ('B', 2) to group
grouped_by A
grouping [('A', 1), ('A', 2)]
grouped_by B
grouping [('B', 1), ('B', 2)]


More information about the Portland mailing list