我的 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
Run Code Online (Sandbox Code Playgroud)
由于我不仅在定时事件中使用,而且使用任何我可以排序的东西(所以它们以某种方式具有可比性),我问:有一种通用的方式,或者一个已知的库可以做到这一点?
Python 没有等效的功能。你必须自己写。
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
Run Code Online (Sandbox Code Playgroud)
可以这样使用:
>>> list(chunk_while([1, 3, 2, 5, 5], lambda prev, next_: next_ <= prev + 2))
[[1, 3, 2], [5, 5]]
Run Code Online (Sandbox Code Playgroud)