[英]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.