如果前一个元素的偏移量等于下一个元素的开始,则组合一个开始偏移元组列表

Combining a list of onset-offset tuples if the previous element's offset equals the next element's onset

是否有任何标准库 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 函数即可。

抱歉,如果这个问题已经被问到,我不确定如何表达这个问题,但这可以看作是起始和偏移的列表,我想合并具有 adjacent/equivalent 时间的元素。

编辑:受下面@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+)\,', '', 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+?)+\,', '', floatspan)
    # convert back to list
    return [tuple(map(float, _.split('-'))) for _ in floatspan.split(',')]

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)]