Home > Blockchain >  Merging lists/tuples stored inside a list in python
Merging lists/tuples stored inside a list in python

Time:11-08

I have a list of lists each containing tuples with some co-ordinates which sort of look like this:

[[(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)]]

Considering orders, lets call the outer list - L0, and the inner list - L1

The number of tuples inside of L1 may vary with incoming data but will be constant for all elements of L0. For example, if there are 3 tuples in L1, there will be 3 tuples in all the rest of the lists.

My goal is to get minimum values of all xn co-ordinates and the maximum values of all yn co-ordinates across all L1 elements and return a list which looks something like this:

[(x1min, y1max), (x2min, y2max), (x3min, y3max) ... (xnmin, ynmax)]

I tried approaching this by looping through L0 and then again looping through L1 only to get individual elements and then trying to construct a new list of the expected output but it is very long and I think would be inefficient.

I am not at all able to figure out how to approach this problem and I am pretty sure there is a very clever and efficient way of solving this. I would be really grateful for any help I can get on this.

Note: I am a newbie learning python so please forgive me if I am accidently using any wrong terms and stuff. Also, this problem might probably be a very easy one but I cannot develop a method to approach this yet. I also tried searching for it everywhere but couldn't find a solution that fits my problem.

CodePudding user response:

A short and relatively fast way to do this would be to use list comprehensions:

xmin = min([x for L1 in L0 for x, y in L1])
ymax = max([y for L1 in L0 for x, y in L1])

Basically, you loop through the lists L1 in the list L2 and make a new list containing all the first (for x) or last (for y) elements of the tuples. Then you call min or max on these new lists which gives you the maximum or minimum argument.

Just for understanding purposes: This list comprehension [x for L1 in L0 for x, y in L1] is equivalent to constructing a new list of all x values with an explicit for-loop like this:

xelements = []
for L1 in L0:
    for coordinates in L1:
        xelements.append(coordinates[0])

CodePudding user response:

You have a list comprised of other lists. Let's call them sub-lists. Each sub-list contains a number of 2-tuples. The challenge appears to be to find the minimum value of all 0th elements of the tuples within a sub-list and the maximum value of the 1th element.

If that's the case then (with some invented numbers), you could do this:

L = [[(-1, 2), (0, 4)], [(1, 6), (2, 9)]]
M = []

for e in L:
    _min = min(t[0] for t in e)
    _max = max(t[1] for t in e)
    M.append((_min, _max))

print(M)

Output:

[(-1, 4), (1, 9)]
  • Related