简体   繁体   English

合并两个Python元组列表

[英]Merge two Python list of tuples

I have two lists of tuples. 我有两个元组列表。 Each tuple contains a datetime object and a float object ie: 每个元组包含一个datetime对象和一个float对象,即:

l1 = [(dt1), 1.0), (dt2, 2.0), (dt3, 3.0)]
l2 = [(dt1), 1.0), (dt3, 3.0), (dt5, 6.0)]

The two lists are already sorted by the datetime of each tuple. 这两个列表已按每个元组的日期时间排序。

What would be a fast way to merge the two lists ? 合并两个列表的快速方法是什么?

The two lists may not contain the same datetimes. 这两个列表可能不包含相同的日期时间。 If one dt exists in one list but not the other the missing value can be '' 如果一个dt存在于一个列表中,但另一个列表不存在,则缺失值可以为''

So for example using the two lists above I would like to produce 因此,例如,使用上面的两个列表,我想生成

l = [(dt1), 1.0, 1.0), (dt2, 2.0, ''), (dt3, 3.0, 3.0), (dt5, '', 6.0)]

I'm guessing maybe I should use a dictionary with the dt as key and then resort but that seems wasteful. 我猜测也许我应该使用以dt为键的字典,然后再诉诸法律,但这似乎很浪费。

Any other ideas ? 还有其他想法吗?

Thanks 谢谢

l1 = [("a", 1.0), ("b", 2.0), ("c", 3.0)]
l2 = [("a", 1.0), ("c", 3.0), ("d", 6.0)]


i1 = 0
i2= 0
l = []
while i1 != len(l1) or i2!=len(l2):
    print i1,i2
    if ((i1<len(l1))and(i2<len(l2))) and l1[i1] ==l2[i2]:
        l.append((l1[i1][0],l1[i1][1],l2[i2][1]))
        i1 +=1
        i2+=1
    elif ((i1<len(l1)and i2<len(l2)) and l1[i1] <l2[i2]) or (i1<len(l1)and i2>=len(l2)):
        l.append((l1[i1][0],l1[i1][1],""))
        i1 +=1

    elif ((i2<len(l2)and i1<len(l1)) and l1[i1] >l2[i2])or (i1>=len(l1)and i2<len(l2)):
        l.append((l2[i2][0],l2[i2][1],""))
        i2 +=1    

I think I fixed the edge cases now too. 我想我现在也修复了一些极端情况。

In case it's useful, I used a different approach: 如果有用,我使用了另一种方法:

result = []
d2 = dict(l2)
for i in l1:
    j = ''
    if i[0] in d2:
        j = d2[i[0]]
        d2.pop(i[0], None)
    result.append((i[0], i[1], j))

for key in d2:
    result.append((key, '', d2[key]))

Mine is about the same efficiency as Moe's answer. 我的效率与萌的答案差不多。 Notice the second value in the tuple in the second list is always placed as the third element in the tuple in the merged list 请注意,第二个列表中元组中的第二个值始终作为合并列表中元组中的第三个元素放置

Result is Merge_List(l1,l2) , where Merge_List is: 结果是Merge_List(l1,l2) ,其中Merge_List是:

def Merge_List(Left,Right,Merged=[]):
    if len(Left)==0 and len(Right)==1:
        return Merged+[(Right[0][0],"",Right[0][1]),]
    elif len(Right)==0 and len(Left)==1:
        return Merged+[Left[0]+("",),]
    else:
        if Left[0][0] < Right[0][0]:
            return Merge_List(Left[1:],Right,
                           Merged=Merged+[Left[0]+("",),])
        elif Right[0][0] < Left[0][0]:
            return Merge_list(Left,Right[1:],
                           Merged=Merged+[(Right[0][0],"",Right[0][1]),])
        else:
            return Merge_List(Left[1:],Right[1:],
                           Merged=Merged+[(Left[0][0],Left[0][1],Right[0][1]),])

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

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