gpt4 book ai didi

Python 等同于 Ruby 的 chunk_while?

转载 作者:太空宇宙 更新时间:2023-11-03 14:41:42 25 4
gpt4 key购买 nike

我的 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 没有等效的函数。您必须自己编写。

这是我的实现,使用 iteratoryield 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]]

关于Python 等同于 Ruby 的 chunk_while?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com