【问题标题】:Combining a list of onset-offset tuples if the previous element's offset equals the next element's onset如果前一个元素的偏移量等于下一个元素的起始点,则组合一个起始偏移元组列表
【发布时间】:2021-08-25 20:43:10
【问题描述】:

是否有任何标准库 Python 或 Numpy 操作用于执行以下操作:

my_array = [(1, 3), (3, 4), (4, 5), (5, 7), (10, 12), (12, 17), (21, 24)]
new_array = magic_function(my_array)
print(new_array)
> [(1, 7), (10, 17), (21, 24)]

我觉得itertools 中的某些东西应该能够做到这一点,似乎很多人都会使用它。我们可以假设列表已经按开始时间排序。无论如何,这样做并不难,您只需在第一个元素上使用带有键的sorted 函数。

抱歉,如果这个问题已经被问过,不知道如何表达这个问题,但这可以被视为起始和偏移的列表,我想合并具有相邻/等效时间的元素。

编辑:受下面@chris-charley 的回答的启发,它依赖于一些第三方模块,我只是写了一个小函数来做我想要的。

import re
def magic_function(mylist):
    # convert list to intspan
    intspan = ','.join([f'{int(a)}-{int(b)}' for (a,b) in mylist])
    # collapse adjacent ranges
    intspan = re.sub(r'\-(\d+)\,\1', '', intspan)
    # convert back to list
    return [tuple(map(int, _.split('-'))) for _ in intspan.split(',')]

以下是浮点数的泛化函数:

import re
def magic_function(mylist):
    # convert list to floatspan
    floatspan = ','.join([f'{float(a)}-{float(b)}' for (a,b) in mylist])
    # collapse adjacent ranges
    floatspan = re.sub(r'\-(\d+\.?\d+?)+\,\1', '', floatspan)
    # convert back to list
    return [tuple(map(float, _.split('-'))) for _ in floatspan.split(',')]

【问题讨论】:

    标签: python numpy sorting list-comprehension


    【解决方案1】:

    intspan 具有 from_ranges()ranges() 方法来产生您需要的结果。

    >>> from intspan import intspan
    >>> my_array = [(1, 3), (3, 4), (4, 5), (5, 7), (10, 12), (12, 17), (21, 24)]
    >>> intspan.from_ranges(my_array).ranges()
    [(1, 7), (10, 17), (21, 24)]
    

    【讨论】:

    • 感谢@chris-charley,我已使用受您链接的这个 intspan 模块启发的解决方案编辑了原始帖子。
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2017-05-02
    • 2018-12-06
    • 2017-06-16
    • 2022-01-08
    相关资源
    最近更新 更多