繁体   English   中英

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

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

我有两个元组列表:

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

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

我想要合并列表。

期望的输出:

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

我想 zip,但有点错误。 [(('PL42222941176247135539240187',), (10002,)), (('PL81786645034401957047621964',), (10003,)), (('PL61827884040081351674977449',), (10004,))...]

如何获得所需的 output?

当您使用zip进行迭代时,只需解构单元素元组:

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

似乎 zip 失败了,因为你有一个元组列表而不仅仅是一个列表。 事实上,它创建了一个元组的元组列表。 在传入 zip 之前转换您的元组列表:

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

joined_result = list(zip(result1, result))

或在一行中:

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

利用:

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

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

newResult = []

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

警告:它会破坏 result1,所以在循环之前的某个地方会破坏 result2 = result1

暂无
暂无

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

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