Zanam Zanam - 2 months ago 7
Python Question

Organizing list of tuples

I have a list of tuples which I create dynamically.

The list appears as:

List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)]


Each tuple
(a, b)
of list represents the range of indexes from a certain table.

The ranges
(a, b) and (b, d)
is same in my situation as
(a, d)


I want to merge the tuples where the 2nd element matches the first of any other.

So, in the example above, I want to merge
(8, 10), (10,13)
to obtain
(8,13)
and remove
(8, 10), (10,13)


(19,25) and (25,30)
merge should yield
(19, 30)


I don't have a clue where to start. The tuples are non overlapping.

Edit: I have been trying to just avoid any kind of for loop as I have a pretty large list

Answer

non-recursive approach, using sorting (I've added more nodes to handle complex case):

l = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30), (30,34), (38,40)]
l = sorted(l)

r=[]
idx=0

while idx<len(l):
    local=idx+1
    previous_value = l[idx][1]
    # search longest string
    while local<len(l):
        if l[local][0]!=previous_value:
            break
        previous_value = l[local][1]
        local+=1
    # store tuple
    r.append((l[idx][0],l[local-1][1]))
    idx = local


print(r)

result:

[(1, 4), (8, 13), (14, 16), (19, 34), (38, 40)]

The only drawback is that original sort order is not preserved. I don't know if it's a problem.