繁体   English   中英

Itertools.accumulate查找间隔的并集(从减少转换为累积)

[英]Itertools.accumulate to find union of intervals (convert from reduce to accumulate)

我似乎已经开发出正确的reduce操作来找到间隔的并集,只是意识到reduce给您最终的结果。 因此,我查阅了文档,发现实际上我应该使用的是accumulate

我需要某人来帮助我将此reduce转换为accumulate所以我有中间间隔

以下代码是我如何使用reduce的示例。 我假设可以使用accumulate存储中间值。 我不确定这是否可能。.但是我看了一些例子,“ accumulate如何为您提供项目列表,其中每个项目都是中间计算结果。

example_interval = [[1,3],[2,6],[6,10],[15,18]]

def main():

    def function(item1, item2):


        if item1[1] >= item2[0]:

            return item1[0], max(item1[1], item2[1])

        else:

            return item2

    return reduce(function, example_interval)

为了理解问题,可以将[1, 3], [2, 6]简化为[1, 6]因为item1[1] >= item2[0] ,然后将[1, 6]用作item1 ,然后与为item2 [6,10]进行比较, item2 [1, 10] item2 [1, 10] [1, 10]然后与最终产品相比较[15, 18]在这种情况下,就不会合并,因此最终结果为[1, 10], [15, 18]

我确实知道如何解决这个问题而不reduceaccumulate 我只是对了解如何使用accumulate来复制此任务(存储中间值)感兴趣。

from itertools import accumulate

def function(item1, item2):
    if item1[1] >= item2[0]:
        return item1[0], max(item1[1], item2[1])
    return item2

example_interval = [(1,3),(2,6),(6,10),(15,18)]
print(list(accumulate(example_interval, function)))

结果是:

[(1, 3), (1, 6), (1, 10), (15, 18)]

注意,我将example_interval上的项目从列表更改为元组。 如果不这样做,则当item1[1] < item2[0] ,返回值是作为列表对象的item2 ,但是如果item[1] >= item2[0] ,则返回表达式是item1[0], max(item1[1], item2[1]) ,将其转换为元组:

example_interval = [[1,3],[2,6],[6,10],[15,18]]
print(list(accumulate(example_interval, function)))

现在的输出是:

[[1, 3], (1, 6), (1, 10), [15, 18]]

暂无
暂无

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

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