简体   繁体   English

合并元组列表中的元组

[英]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) : 像这样的(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. 合并后,如果超过的任何元组仍包含None值,则应将其切除或附加在末尾。

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? python中有什么方法可以做到这一点吗?

Thanks for your help! 谢谢你的帮助!

Try this nested list comprehension using zip: 尝试使用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)]

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

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