python: many to many groupings using iterator module -
i have iterable, items of map multiple groups. how group items using iterator module?
animals = (human, frog, giraffe, fish)
here human, frog, etc objects attributes: is_land_dwelling , is_water_dwelling.
i want group animals based on these attributes
groupings = dwelling_classifier(animals)
should return group iterator splits animals into
is_land_dwelling: human, frog, giraffe is_water_dwelling: frog, fish
i prefer make single pass on iterable. so, apart writing custom iterator function, there other way?
def is_water_dwelling(animal): return animal in ('frog', 'fish') def is_land_dwelling(animal): return animal in ('frog', 'human', 'giraffe') animals = ('human', 'frog', 'fish', 'giraffe') land_dwelling = (x x in animals if is_land_dwelling(x)) water_dwelling = (x x in animals if is_water_dwelling(x)) print list(land_dwelling) print list(water_dwelling)
note land_dwelling
, water_dwelling
generators.
this can generalized amount of "classifiers", holding relevant classification functions in dictionary of kind, possibly keyed classification type. (not tested):
kinds = {'water': is_water_dwelling, 'land': is_land_dwelling, 'air': is_flying} result = {} kind, classifier in kinds.iteritems(): result[kind] = [x x in animals if classifier(x)] # if want go on animals once, can instead: collections import defaultdict result = defaultdict(list) x in animals: kind, classifier in kinds.iteritems(): if classifier(x): result[kind].append(x)
Comments
Post a Comment