Return to Snippet

Revision: 699
at July 31, 2006 20:12 by newtonapple


Updated Code
def partition(iterable, func):
    result = {}
    for i in iterable:
        result.setdefault(func(i), []).append(i) 
    return result

def group(seq):
    result = {}
    for item, category in seq:
        result.setdefault(category, []).append(item)
    return result 

# def is_odd(n):
#     return (n%2) == 1
# l = range(100)
# print partition(l, is_odd)
# print group( (item, is_odd(item)) for item in l)
# print group( (item, item%11) for item in l)    # no need to use lamda/def

Revision: 698
at July 31, 2006 20:08 by newtonapple


Initial Code
def partition(iterable, func):
    result = {}
    for i in iterable:
        result.setdefault(func(i), []).append(i) 
    return result

def group(seq):
    result = {}
    for item, category in seq:
        result.setdefault(category, []).append(item)
    return result 

Initial URL

                                

Initial Description

                                

Initial Title
Partitioning a sequence into a dictionary keyed by function values

Initial Tags
list, python, function

Initial Language
Python