我有两个元组列表:
result = [(10002,), (10003,), (10004,), (10005,)...]
result1 = [('PL42222941176247135539240187',), ('PL81786645034401957047621964',), ('PL61827884040081351674977449',)...]
我想要合并列表。
期望的输出:
joined_result = [('PL42222941176247135539240187', 10002,), ('PL81786645034401957047621964', 10003,),('PL61827884040081351674977449', 10004,)...]
我想到了 zip,但有点不对。
[(('PL42222941176247135539240187',), (10002,)), (('PL81786645034401957047621964',), (10003,)), (('PL61827884040081351674977449',), (10004,))...]
如何获得所需的输出?
答案 0 :(得分:2)
当您使用 zip
进行迭代时,只需解构单元素元组:
joined_result = [(x, y) for ((x,), (y,)) in zip(result1, result)]
答案 1 :(得分:0)
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]))
答案 2 :(得分:0)
使用:
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