简体   繁体   English

将列表元素与元组元素合并

[英]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我想通过以下方式将每个元素数组合并为列表或 NumPy 数组

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 TypeError:只能将元组(不是“str”)连接到元组

Could you point me in the right direction?你能指出我正确的方向吗?

Using the additional unpacking generalizations of modern (3.5+) Python, this isn't so hard:使用现代(3.5+)Python的额外解包概括,这并不难:

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

The tuple s 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 tuple s. tuple*解包,而单个元素通常只包含在tuple文字中,无需显式地将L1中的元素包装在tuple中,也无需执行多个连接产生中间临时tuple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM