简体   繁体   中英

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. [(('PL42222941176247135539240187',), (10002,)), (('PL81786645034401957047621964',), (10003,)), (('PL61827884040081351674977449',), (10004,))...]

How get desired output?

Just destructure the single-element tuples when you iterate using 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. In fact it creates a list of tuples of tuples. Convert your list of tuples before passing in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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