简体   繁体   中英

Merging tuples in list of tuples

Say there is a list of tuples where in each tuple can only contain unique characters/numbers and the order and length of each tuple is the same. like this, a list of tuples of (1, 2, 3) :

l = [
    (1   ,    2,    3), #1  
    (None,    2,    3), #2 merge with #4 or #8
    (1   , None,    3), #3 merge with #6
    (1   , None, None), #4 overhead?
    (1   ,    2,    3), #5
    (None,    2, None), #6
    (1   ,    2, None), #7 overhead
    (1   , None, None), #8 overhead?
    ]

But in some tuples values are missing and the missing values should be merged/ complemented with matching tuples from the same list. After merging, if any tuples are over that still contain a None value, they should be cut off or appended at the end.

Designated Result:

l = [
    (1   ,    2,    3), #1  
    (1   ,    2,    3), #2 merged with #4
    (1   ,    2,    3), #3 merged with #6
    (1   ,    2,    3), #4
    ]

Is there any way in python to do this?

Thanks for your help!

Try this nested list comprehension using zip:

list(zip(*[[f for f in e if f] for e in zip(*l)]))

Outputs:

[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]

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