按键组合两个元组列表

时间:2015-05-20 09:00:30

标签: python list tuples

我有两个元素元组的列表。元组的第一个元素是ID,第二个元素是某种值。值的类型取决于列表。

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

将它们组合成最简单的方法是什么:

lst3 = [ ('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

3 个答案:

答案 0 :(得分:4)

我建议您先将这些元组列表转换为字典。然后,假设两个列表包含相同的“键”,您可以使用简单的列表推导来从两个词典中获取相应的值。

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 
dict1 = dict(lst1)
dict2 = dict(lst2)
lst3 = [(k, dict1[k], dict2[k]) for k in sorted(dict1)]

请注意,词典没有固定的顺序。如果您想保留密钥在lst1中的顺序,您也可以使用此功能,如评论中所示:

lst3 = [(k, v, dict2[k]) for k, v in lst1]

答案 1 :(得分:0)

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

dst1 = dict(lst1)
dst2 = dict(lst2)

for i in dst1:
    if i in dst2:
        dst1[i] = (dst1[i],dst2[i])

print dst1
{'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}

然后,您可以将dst1格式化为您想要的结果格式。

答案 2 :(得分:0)

你只需要使用来自lst1的每个元组的第一个元素作为键创建一个dict,并将元组存储为值,然后迭代第二个列表并将最后一个元素添加到dict中相应的元组。 / p>

Dim s As New NotesSession
Dim db As NotesDatabase
Dim ws As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Dim currField As String
Dim rtitem As NotesRichTextItem
Dim style As NotesRichTextStyle
Dim color As NotesColorObject

Set uidoc = ws.Currentdocument
Set db = s.Currentdatabase
Dim DummyDoc As NotesDocument
Dim DummyRT As NotesRichTextItem

currField = uidoc.Currentfield

'Insert Section
Set DummyRT = uidoc.Document.Getfirstitem(currField)
Call DummyRT.Beginsection("",style,color,true)
Call DummyRT.Appendtext("Test")
Call DummyRT.Endsection()
Call uidoc.Reload()

Call uidoc.Gotofield(currField)

Call uidoc.Paste()