假设我有一个自动增加几个计数器的过程。然而,一些外部操作,即人类交互,会重置这些计数器。一段时间后,计数器重新对齐。
从数据的角度来看,我留下的计数器在特定的点上有一个断裂,我想要对齐它们。
计数器如下所示:
counter = [1, 1, 2, 3, 3, 4, 5, 6, 1, 1, 2, 2, 3, 10, 11, 12]
我想解决这些问题:
counter = [1, 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 8, 9, 10, 11, 12]
我有很多带有这样的计数器的专栏,我正在考虑一种整洁的方法,首先找到破裂,然后修复它。
发布于 2021-07-22 22:22:34
如果您希望在列表中逐个元素执行此操作,则可以将此序列转换为:
offset = 0 # after a reset, save how much we're off by
for i in range(1, len(counter)):
if counter[i] - counter[i - 1] >= 0: # if sequence is stable or increasing, no action needed
offset = 0 # though if it just became so, reset the offset
else:
if offset == 0: # if this is the first out-of-order element,
offset = value # set the offset based on current value
counter[i] += offset # and update the value with the offset有几个注意事项。首先,如果在返回到表单之前有多次重置,这将无法正常工作。您可以通过将最后一个元素的实际值存储在一个变量中,检查是否有另一次减少,并相应地更新偏移量,从而检测到这一点。
其次,可能有更有效的方法来实现这一点,特别是如果您使用的是像pandas dataframe这样的结构,而不是普通的python列表。不过,这些不是我的专业领域,所以我不知道它们会是什么。
https://stackoverflow.com/questions/68486146
复制相似问题