我有一个可迭代的,其中的项目映射到多个组。如何使用迭代器模块对项目进行分组?
animals = (human, frog, giraffe, fish)
此处,人类,青蛙等是具有属性的对象:is_land_dwelling和is_water_dwelling。
我想根据这些属性对动物进行分组
groupings = dwelling_classifier(animals)
应该返回一些将动物分成
的组迭代器is_land_dwelling: human, frog, giraffe
is_water_dwelling: frog, fish
我宁愿只对iterable进行单次传递。那么,除了编写我的自定义迭代器函数之外,还有其他方法吗?
答案 0 :(得分:3)
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 for x in animals if is_land_dwelling(x))
water_dwelling = (x for x in animals if is_water_dwelling(x))
print list(land_dwelling)
print list(water_dwelling)
请注意,land_dwelling
和water_dwelling
是生成器。
通过将相关的分类函数保存在某种类型的字典中,可以通过分类类型进行键控,可以对任何数量的“分类器”进行推广。这样的事情(未经测试):
kinds = {'water': is_water_dwelling, 'land': is_land_dwelling, 'air': is_flying}
result = {}
for kind, classifier in kinds.iteritems():
result[kind] = [x for x in animals if classifier(x)]
# If you just want to go over animals once, you can do this instead:
from collections import defaultdict
result = defaultdict(list)
for x in animals:
for kind, classifier in kinds.iteritems():
if classifier(x):
result[kind].append(x)