python:iterator.groupby 的宽松版本,跳过异常记录
我使用 iterator.groupby 根据如下属性值将迭代器中的相似条目分组在一起:
employment = dict(itertools.groupby(xtable_iterator), operator.attrgetter('key_to_ytable')))
key_to_ytable 是一个可以引发异常的属性。所以,我的整个字典构造函数失败了。我想跳过“key_to_ytable”属性访问引发异常的条目,并使用 groupby 处理剩余条目。
我有什么选择?
1.继承groupby并覆盖函数或编写我的自定义groupby
2. 使用自定义 attrgetter,在异常时返回 None,然后过滤掉 None
3.还有其他解决办法吗?
一些背景:我有一个库,它将数据库表封装为记录对象的迭代器。该记录对象的属性是列。如果是外键,库会查找相应的表并获取该值作为属性值。不幸的是,不能保证这些表是同步的。因此,外键可能引用不存在的记录,在这种情况下,库会抛出异常。
I am using a iterator.groupby to group similar entries in an iterator together based on an attribute value like this:
employment = dict(itertools.groupby(xtable_iterator), operator.attrgetter('key_to_ytable')))
key_to_ytable is an attribute that can throw an exception. So, my whole dict constructor fails. I would like to just skip the entries for which the 'key_to_ytable' attribute access throws exception and process the remaining entries using groupby.
What are my alternatives?
1. Inherit from groupby and override functions OR write my custom groupby
2. Use a custom attrgetter that returns None on exception and then filter out the Nones
3. Any other solution?
Some background: I have a library that encapsulates the database table as an iterator of record object. The attributes of this record object are the columns. In case of foreign key, the library looks up the corresponding table and fetches the value as an attribute value. Unfortunately, the tables are not guaranteed to be in sync. So, a foreign key may refer to an non-existent record, in which case, the library throws an exception.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,我投票支持自定义 attrgetter,例如:
这比执行过滤器或任何其他操作更简单,而且可能更快,你知道那里只会有一个 None 。
I vote for the custom attrgetter in this situation, like:
This is simpler and probably faster than doing a filter or anything, you know there will only be one None there.