簡體   English   中英

合並兩個Python元組列表

[英]Merge two Python list of tuples

我有兩個元組列表。 每個元組包含一個datetime對象和一個float對象,即:

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

這兩個列表已按每個元組的日期時間排序。

合並兩個列表的快速方法是什么?

這兩個列表可能不包含相同的日期時間。 如果一個dt存在於一個列表中,但另一個列表不存在,則缺失值可以為''

因此,例如,使用上面的兩個列表,我想生成

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

我猜測也許我應該使用以dt為鍵的字典,然后再訴諸法律,但這似乎很浪費。

還有其他想法嗎?

謝謝

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    

我想我現在也修復了一些極端情況。

如果有用,我使用了另一種方法:

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]))

我的效率與萌的答案差不多。 請注意,第二個列表中元組中的第二個值始終作為合並列表中元組中的第三個元素放置

結果是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