简体   繁体   English

python:宽版本的iterator.groupby会在出现异常时跳过记录

[英]python: lenient version of iterator.groupby that skips the records on exception

I am using a iterator.groupby to group similar entries in an iterator together based on an attribute value like this: 我正在使用iterator.groupby根据类似这样的属性值将迭代器中的相似条目组合在一起:

 employment = dict(itertools.groupby(xtable_iterator), operator.attrgetter('key_to_ytable')))  

key_to_ytable is an attribute that can throw an exception. key_to_ytable是可以引发异常的属性。 So, my whole dict constructor fails. 因此,我的整个dict构造函数都失败了。 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. 我只想跳过“ key_to_ytable”属性访问引发异常的条目,并使用groupby处理其余条目。

What are my alternatives? 我有什么选择?
1. Inherit from groupby and override functions OR write my custom groupby 1.从groupby继承并覆盖函数,或者编写我的自定义groupby
2. Use a custom attrgetter that returns None on exception and then filter out the Nones 2.使用一个自定义attrgetter,该attrgetter在异常时返回None,然后过滤掉None
3. Any other solution? 3.还有其他解决方案吗?

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. 因此,外键可能引用了不存在的记录,在这种情况下,库将引发异常。

I vote for the custom attrgetter in this situation, like: 在这种情况下,我投票支持自定义属性,例如:

employment = dict(itertools.groupby(xtable_iterator),
                  lambda x: getattr(x, 'key_to_ytable', None))
employment.pop(None)

This is simpler and probably faster than doing a filter or anything, you know there will only be one None there. 这比做过滤器或其他任何方法都更简单,并且可能更快,您知道那里只有一个None。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM