我的 Ruby 代码中有一些有趣的用例,我想将它们转换为 Python。我认为我们可以利用任何库,我主要使用 pandas 和 numpy。
例如,假设您有一组定时事件,这些事件具有时间戳和其他属性(对象或元组)。
我想要一个组列表/数组,其中这些组是“连续”事件,宽限期为 g
单位(在本例中为时间单位)。
在我的 Ruby 代码中,我使用这样的东西:
grouped_events = events.chunk_while do |previous_event, next_event|
next_event.timestamp <= previous_event.timestamp + grace_period
end
因为我不仅在定时事件中使用,而且在我可以排序的任何东西中使用(所以它们在某种程度上是可比较的),我问:有一个通用的方法,或者一个已知的库可以做到这一点?
Python 没有等效的函数。您必须自己编写。
这是我的实现,使用 iterator和 yield
statement :
def chunk_while(iterable, predicate):
itr = iter(iterable)
try:
prev_value = next(itr)
except StopIteration:
# if the iterable is empty, yield nothing
return
chunk = [prev_value]
for value in itr:
# if the predicate returns False, start a new chunk
if not predicate(prev_value, value):
yield chunk
chunk = []
chunk.append(value)
prev_value = value
# don't forget to yield the final chunk
if chunk:
yield chunk
可以这样使用:
>>> list(chunk_while([1, 3, 2, 5, 5], lambda prev, next_: next_ <= prev + 2))
[[1, 3, 2], [5, 5]]
我是一名优秀的程序员,十分优秀!