简体   繁体   English

合并两个元组列表。 具有两个元素的所需元组列表

[英]Merge two lists of tuples. Desired list of tuples with two elements

I have two lists of tuples:我有两个元组列表:

result = [(10002,), (10003,), (10004,), (10005,)...]

result1 = [('PL42222941176247135539240187',), ('PL81786645034401957047621964',), ('PL61827884040081351674977449',)...]

I want merge lists.我想要合并列表。

DESIRED OUPUT:期望的输出:

joined_result = [('PL42222941176247135539240187', 10002,), ('PL81786645034401957047621964', 10003,),('PL61827884040081351674977449', 10004,)...]

I think about zip, but is litte wrong.我想 zip,但有点错误。 [(('PL42222941176247135539240187',), (10002,)), (('PL81786645034401957047621964',), (10003,)), (('PL61827884040081351674977449',), (10004,))...]

How get desired output?如何获得所需的 output?

Just destructure the single-element tuples when you iterate using zip :当您使用zip进行迭代时,只需解构单元素元组:

joined_result = [(x, y) for ((x,), (y,)) in zip(result1, result)]

It seems zip fails because you have a list of tuples not only a list.似乎 zip 失败了,因为你有一个元组列表而不仅仅是一个列表。 In fact it creates a list of tuples of tuples.事实上,它创建了一个元组的元组列表。 Convert your list of tuples before passing in zip:在传入 zip 之前转换您的元组列表:

result = [x[0] for x in result]
result1 = [x[0] for x in result1]

joined_result = list(zip(result1, result))

or in one line:或在一行中:

joined_result = list(zip([x[0] for x in result1],[x[0] for x in result]))

Use:利用:

result = [(10002,), (10003,), (10004,)]

result1 = [('PL42222941176247135539240187',), ('PL81786645034401957047621964',), ('PL61827884040081351674977449',)]

newResult = []

for i in range(len(result)):
    result1[i] += result[i]
    newResult.append(result1[i])

Warning:, it will break result1, so do result2 = result1 somewhere before the loop警告:它会破坏 result1,所以在循环之前的某个地方会破坏 result2 = result1

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

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