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

时间:2019-01-31 00:34:05

标签: python intervals itertools functools 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并与{{ 1}}即[6,10],得到item2。然后将[1, 10]与最终项目[1, 10]进行比较,在这种情况下,它不会合并,因此最终结果为[15, 18]

我确实知道如何在没有[1, 10], [15, 18]reduce的情况下解决此问题。 我只是对了解如何使用accumulate复制此任务(存储中间值)感兴趣。

1 个答案:

答案 0 :(得分:1)

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]]
相关问题