ash
ash

Reputation: 55

How to append elements to a pair of coordinates to make a multidimensional list?

I have a list containing the pair of coordinates as following:

index = [(1, 4), (3, 6), (7, 10), (3, 9)]

now I have list with same size as following:

size = [2, 2, 4, 4]

Now I would like to append the "size" to "index" in order to look like the following:

new = [(1,4,2), (3,6,2), (7,10,4), (3,9,4)]

I have tried a bunch of stuff such as "zip" or "numpy.dstack((index, size)).shape"

but does not give me desired format.

Thank you.

Upvotes: 0

Views: 40

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

You can try this.

[i+(j,) for i,j in zip(index,size)]
# [(1, 4, 2), (3, 6, 2), (7, 10, 4), (3, 9, 4)]

Timeit analysis:

# When list size is 4
In [142]: timeit [(*i,j) for i,j in zip(index, size)] #yatu's answer
1.24 µs ± 72.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [144]: timeit [i+(j,) for i,j in zip(index,size)] #Ch3steR's answer
902 ns ± 28.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

When list of tuples size over 10,000.

In [149]: timeit [(*i,j) for i,j in zip(index, size)]
1.68 ms ± 77.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [150]: timeit [i+(j,) for i,j in zip(index,size)]
1.18 ms ± 27.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Little faster than unpacking approach

Upvotes: 2

yatu
yatu

Reputation: 88226

You can use a list comprehension with zip to aggregate both iterables, then create a new tuple by unpacking the tuples in index and adding the integers in size to it:

[(*i,j) for i,j in zip(index, size)]
# [(1, 4, 2), (3, 6, 2), (7, 10, 4), (3, 9, 4)]

Upvotes: 4

Related Questions