簡體   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