python:使用迭代器模块进行多对多分组
我有一个可迭代的项目,其中的项目映射到多个组。如何使用迭代器模块对项目进行分组?
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
我宁愿只对可迭代对象进行一次传递。那么,除了编写我的自定义迭代器函数之外,还有其他方法吗?
I have an iterable, items of which map to multiple groups. How do I group the items using an iterator module?
animals = (human, frog, giraffe, fish)
Here human, frog, etc are objects with attributes: is_land_dwelling and is_water_dwelling.
I want to group animals based on these attributes
groupings = dwelling_classifier(animals)
should return some group iterator which splits animals into
is_land_dwelling: human, frog, giraffe
is_water_dwelling: frog, fish
I would prefer to make only single pass over the iterable. So, apart from writing my custom iterator function, is there any other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,
land_dwelling
和water_dwelling
是生成器。通过将相关分类函数保存在某种字典中(可能由分类类型键入),可以将其推广到任意数量的“分类器”。像这样的东西(未测试):
Note that
land_dwelling
andwater_dwelling
are generators.This can be generalized for any amount of "classifiers", by holding the relevant classification functions in a dictionary of some kind, possibly keyed by classification type. Something like this (not tested):