Sara Krauss
Sara Krauss

Reputation: 398

Merge a list elements with tuple elements

I have a list and two tuples follows:

L1 = ['0.99999', '0.88888', '0.77777','0.66666','0.55555']

T1 = [('id_099', 'PND', '15.42'),
 ('id_088', 'PKZ', '16.04'),
 ('id_077', 'PZD', '16.73'),
 ('id_066', 'PNK', '18.19'),
 ('id_055', 'PNT', '10.62')]

T2 = [('XX13', 'XY13'),
 ('XX43', 'XY26'),
 ('XX77', 'XY13'),
 ('XX19', 'XY03'),
 ('XX93', 'XY13')]

I would like to merge each element array as a list or NumPy array in the following way

NEW = 
('id_099', 'PND', '15.42','0.99999','XX13', 'XY13'),
('id_088', 'PKZ','16.04','0.88888','XX77', 'XY13'),
.
.
.

When it was only tuples it was easy to merge them as follows:

merged = [i+j for i,j in zip(T1,T2)]   

But I couldn't find an easy way to merge each element of a list with the tuples and it throws me an error when I try to apply the above method for the list.

TypeError: can only concatenate tuple (not "str") to tuple

Could you point me in the right direction?

Upvotes: 2

Views: 349

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155497

Using the additional unpacking generalizations of modern (3.5+) Python, this isn't so hard:

merged = [(*i, x, *j) for i, x, j in zip(T1, L1, T2)]   

The tuples get unpacked with *, while the single element is just included normally in a tuple literal, no need to explicitly wrap the elements from L1 in a tuple, nor perform multiple concatenations producing intermediate temporary tuples.

Upvotes: 3

Related Questions