Python:根据 [i][1] 和 [i+1][0] 的差异合并元组数组

Python: Merging array of tuples based on difference of [i][1] and [i+1][0]

我有以下元组数组:

a = [(0, 657), (1088, 1425), (1427, 1755), (2205, 2856)]

我正在尝试根据以下内容将 i 处的元组与 i+1 处的元组合并:

currentTuple = a[i]
nextTuple = a[i+1]

diff = nextTuple[0] - currentTuple[1]

if diff < 10:
   #Merge tuple
else:
   #Append

到目前为止,我能够创建以下代码:

def mergeCloseIndices(indices):
    skip = False
    updatedIndices = []
    for i in range(len(indices)):
        # If the current tuple is merged with the previous, skip it
        if skip:
            skip = False
            if i+1 == len(indices):
                updatedIndices.append(current)
                break
            continue

        current = indices[i]    

        if i+1 == len(indices):
            updatedIndices.append(current)
            break

        next = indices[i+1]

        # Check if current second index is close to next first index
        diff = next[0] - current[1]

        if diff < 10:
            updatedIndices.append((current[0], next[1]))
            skip = True
        else:
            if ~skip:
                updatedIndices.append(current)

    return updatedIndices

这是我的问题:

  1. 对于上面的数组,这个函数有效。但是,它不适用于以下数组:
b = [(137, 459), (885, 1245), (1247, 1573)]
  1. 如果有3个连续的元组需要合并怎么办?我想不出解决这个问题的方法。

干杯!

IIUC:

a = [(0, 657), (1088, 1425), (1427, 1755), (2205, 2856)]

stack = []

while a:
    current = a.pop(0)

    if not stack:
        stack.append(current)
        continue

    last = stack.pop()

    if current[0] - last[1] < 10:
        stack.append((last[0], current[1]))
    else:
        stack.append(last)
        stack.append(current)

print(stack)

打印:

[(0, 657), (1088, 1755), (2205, 2856)]

对于a = [(137, 459), (885, 1245), (1247, 1573)]

[(137, 459), (885, 1573)]

对于a = [(0, 1), (2, 3), (4, 5), (40, 50)]

[(0, 5), (40, 50)]